0

I am appending a value 100 to every line in a file with the code below. This code works well when I run it in terminal but when I save the code in .awk file and run it I am getting an error. How to run this code from a script file instead of running from terminal?

code:  awk -F ';' '{if ($2==NULL) print $0"100"}' example.txt

my.awk

awk -F ';' '{if ($2==NULL) print $0"100"}'

command in terminal

awk -f my.awk example.txt

error

 invalid char ''' in expression. I get this error at ';'

How to rectify this error and run the awk file on example.txt?

1

When executing an awk script with awk -f, the script should only contain the awk code.

In your case

{if ($2==NULL) print $0"100"}

or

$2 == NULL { print $0 "100" }

You would execute this with

awk -F ';' -f my.awk example.txt

If you want to set FS to ; in the script (statically, instead of on the command line with -F), do so in a BEGIN block:

BEGIN { FS = ";" }

$2 == NULL { print $0 "100" }

Note, too, that the variable NULL is unset in your code.

  • Ok. Got it. Thanks. What is meant by NULL is unset? I did not understand that line. – Laxman Apr 11 at 11:44
  • @Laxman You are using a variable called NULL that you haven't given any value. If you want to test whether $2 is empty, just use $2 == "". – Kusalananda Apr 11 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.