LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Help needed with awk (https://www.linuxquestions.org/questions/linux-general-1/help-needed-with-awk-704060/)

khaos83 02-12-2009 12:01 AM

Help needed with awk
 
I am trying to extract information from a file using awk

e.g. My file
Code:

10001  aaa111  bbb222
10002  ccc333  ddd444
10003  eee555  fff666

If I want to extract information of 10001...

Code:

awk '/10001/ { print $1 " " $2 " " $3 }' myfile.txt
The above works. It outputs what i wanted




But if I want to hard code it and pass in the 10001 as a parameter into the script or using a variable...

Code:


mycode=10001

awk '/$mycode/ { print $1 " " $2 " " $3 }' myfile.txt
awk '/$1/ { print $1 " " $2 " " $3 }' myfile.txt

The above does not work. It does nothing and output nothing.
Is there something wrong with it?
I can't figure out why.

colucix 02-12-2009 12:16 AM

You have to put $mycode outside single quotes, otherwise it is not processed by the shell:
Code:

awk '/'$mycode'/ { print $1 " " $2 " " $3 }' myfile.txt
See the Awk Programming Guide about Using Shell Variables in awk programs, for further details.

raut.vijay 02-12-2009 12:24 AM

The '$' sign which u r actually using has a different meaning in awk. I think, the site mentioned below would assist u in solving the problem.

http://www.vectorsite.net/tsawk_2.html#m2

Bye & Good Luck

khaos83 02-12-2009 01:07 AM

thanks!

jschiwal 02-12-2009 01:21 AM

The $mycode variable in post #2 is evaluated by the shell before the arguments are filled out.
Code:

set awk '/'$mycode'/ { print $1 " " $2 " " $3 }' myfile.txt
> echo $1
awk
> echo $2
/1001/ { print $1 " " $2 " " $3 }
> echo $@
awk /1001/ { print $1 " " $2 " " $3 } myfile.txt

Pay attention to what is inside the single quotes and what isn't.


All times are GMT -5. The time now is 06:36 PM.