0

I want to send a variable to my external .awk script to use as a conditional. The following script is however not working.

Here first is the command:

awk -v myVar="optA" -f /users/test/fixit.awk /users/test/input.txt > /users/test/output.txt

The sample fixit.awk script is:

BEGIN { printf "TITLE:\nDocuments \n", myVar, FS=" "; }

if (myVar="optA")
      printf myVar
else 
      printf "OptB"

Can someone please help diagnose the problem?

3
  • You probably don't mean to have a comma before FS=" ". Also, you probably don't even need that FS assignment at all, because the default input field separator is white space. Commented Feb 2, 2016 at 0:29
  • See Assigning Variables on the Command Line from GNU awk documentation. Also, reading a nice tutorial might help too. Commented Feb 2, 2016 at 0:37
  • Thanks e0k, The tutorial link is great! Commented Feb 2, 2016 at 21:54

1 Answer 1

2

An awk assignment is also an expression with the return value of what was assigned. If you write

if (myVar = "optA")

you actually check the return value of the assignment, optA, which awlays evaluates to "true". You want

if (myVar == "optA")

for comparison instead of assignment.

Also, you can't have "naked" statements like this. Your if/else clause either has to be part of the BEGIN block:

BEGIN {
    printf "TITLE:\nDocuments \n", myVar, FS=" "

    if (myVar=="optA")
          printf myVar
    else 
          printf "OptB"
}

to execute once, or in a separate block if it should be executed for every single line (less likely, though):

BEGIN { printf "TITLE:\nDocuments \n", myVar, FS=" " }

{
    if (myVar=="optA")
        printf myVar
    else 
        printf "OptB"
}

As an aside, the way you use printf doesn't make much sense: you could either do

print "TITLE:\nDocuments\n" myVar

or

printf "TITLE:\nDocuments\n%s\n", myVar

And for printf myVar or printf "OptB", unless you explicitly don't want that newline, you can as well use print myVar and print "OptB".

And finally, that FS= assignment looks a bit out of place and is probably not needed as " " is the default value of FS.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I needed the execution blocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.