LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   passing vars to awk (http://www.linuxquestions.org/questions/programming-9/passing-vars-to-awk-366290/)

schneidz 09-23-2005 11:22 AM

passing vars to awk
 
hi lq, i have this bash script, how do i pass the bash variable to the awk command? :

Code:

/temp> cat test.ksh
#!/bin/bash

cycle=$2
echo $cycle
awk                                          \
        '{                                  \
          if($2 == $cycle)                \
          {                                  \
            printf( $0 "  cycle = " $cycle "\n"); \
          }                                  \
        }' $1

/temp> cat test.lst
l33t    h4x0rz  line1
hello  world  line2
chun-li akuma  line3

/temp> test.ksh test.lst world
world
awk: 0602-562 Field $() is not correct.
 The input line number is 1. The file is test.lst.
 The source line number is 2.

thanks all,

druuna 09-23-2005 11:41 AM

Hi,

use -v name="$var" directly after the (n)awk command.

I.e:
Code:

#!/bin/ksh

cycle=$2
echo $cycle
awk -v cycle="$cycle" '
{
  if ( $2 == cycle ) {
    printf("%s cycle = %s\n",$0,cycle)
  }
 }' $1

Output of testrun:
Code:

$ ./test.ksh test.lst world
world
hello  world  line2 cycle = world

I 'corrected' some other stuff as well.

Hope this helps.

jlliagre 09-23-2005 11:45 AM

Another point, it is unwise to name .ksh as extension to a bash script.

schneidz 09-23-2005 11:58 AM

thanks druuna, it works magically.

thanks for the advice jll. (bad habit i suppose).

eddiebaby1023 09-25-2005 10:14 AM

Re: passing vars to awk
 
[QUOTE]Originally posted by schneidz
[B]hi lq, i have this bash script, how do i pass the bash variable to the awk command? :
/quote]
By using quoting sensibly: ;)
Code:

#!/bin/bash

cycle=$2
echo $cycle
awk                                          \
        '{
          if('$2' == $cycle)
          {
            printf( $0 "  cycle = " $cycle "\n");
          }
        }' $1

Spot the extra single quotes I've added. Your lesson for today is to figure out why this makes it work.:D

jlliagre 09-25-2005 10:44 AM

should be
Code:

if('$2' == '$cycle')
...
printf( $0 "  cycle = " '$cycle' "\n");


eddiebaby1023 09-25-2005 01:52 PM

Quote:

Originally posted by jlliagre
should be
Code:

if('$2' == '$cycle')
...
printf( $0 "  cycle = " '$cycle' "\n");


Oops! I was concentrating on passing in $2. Sorry.:(


All times are GMT -5. The time now is 03:02 PM.