Passing a shell script variable into an AWK command

23
2014-04
  • mattm123

    I want to be able to call a shell script contining the following command.

    awk -F $'\xE7' '{OFS ="¬"} { $3 = sprintf("%010s". $3) ; print $0 }' > outputfile
    

    But I want to be able to pass a shell script variable into this command which will be used to replace the $3 within the AWK command.

    How do I pass a shell script variable into this AWK command?

  • Answers
  • Ignacio Vazquez-Abrams

    Single quotes inhibit expansion. Switch them up.

    awk ... '...'"$foo"'...' ...
    
  • Gilles

    The correct way to do this is using AWK's variable passing feature. Also, you probably only need to set OFS once, so you should do it in the BEGIN clause.

    awk -F $'\xE7' -v awkvar="$shellvar" 'BEGIN {OFS ="¬"} { $3 = sprintf("%010s". $3) ; print $0, awkvar }' input file > outputfile
    

    You could also use -v to set OFS:

    awk -F $'\xE7' -v awkvar="$shellvar" -v OFS ="¬" '{ $3 = sprintf("%010s". $3) ; print $0, awkvar }' input file > outputfile
    

    I just added the variable to the print statement since I didn't know exactly how you wanted to use it.

  • Ilia K.

    awk has ENVIRON array for accessing environment:

    $ FOO=bar awk 'BEGIN{print ENVIRON["FOO"]}'
    bar
    

  • Related Question

    awk + match string after "=" seperator
  • lidia

    I have problem with the following awk syntax

        echo " param1 param2 param3 = param1 AA , AB , AC , AD  "  | awk -F"=" '$2~/AA|AB|AC|AD/{print "passed"}'
    

    the awk print passed , but its not shuld be because after "=" I have param1 and not "AA" or AB" etc

    the target of the awk is to print passed only if the string after "=" is AA OR AB OR AC OR AD

    and if I have something else after "=" then its not should print passed

    how to fix the awk syntax?

    lidia


  • Related Answers
  • Gilles

    After the =, you have the string param1 AA , AB , AC , AD. Your awk expression accepts any string that contains AA or AB or AC or AD. If you want these words to appear at the beginning of the field, you need to anchor the pattern (start it with ^ to match only at the beginning, finish it with '$' to match only at the end). For example the following expression requires the field to be only one of the specified words, possibly with spaces before and after:

    $2 ~ /^ *(AA|AB|AC|AD) *$/
    
  • W_Whalley

    This awk expression to search for AA at the beginning of the field is ^AA, or to allow zero or more spaces between = and the AA, it is ^ *AA, so this expression ought to only print passed if the first term after the = is AA OR BB OR AC OR AD preceded by zero or more spaces.

    awk -F"=" '$2~/^ *AA|^ *AB|^ *AC|^ *AD/{print "passed"}'