Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print when field is a certain value 2

Status
Not open for further replies.

TheDash

MIS
Mar 25, 2004
171
US
Hi,

I would like to print all lines of a file where the second field $2 is abc. Could that be done using awk? If not please let me know what can be used. Thanks.
 
The simplest awk way:
Code:
awk '$2=="abc"' /path/to/input

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks PHV.

awk '$2==$var {print $2}' /path/to/input

I also used

cat /path/to/input | awk 'match($2,"$var") == 0 {print $2}'`

They are not working for some reason. Any ideas please. Thanks again.
 
because first of all, $ doesn't work inside single quotes...
and second, if $ would work inside single quotes, you'd have some trouble getting the $ character in $2 and you'd be comparing $2 to the awk variable with name as specified by $awk ...

so:

wrong: awk '$2==$var' /path/to/file
(amounts to awk '$2==$0' /path/to/file)
wrong: awk "\$2==$var" /path/to/file
(if in shell var="abc", amounts to awk "$2==abc" /path/to/file
which is probably awk "$2==0" /path/to/file)

some solutions:

right: awk "\$2==\"$var\"" /path/to/file (use double quotes, escape special chars where needed)
right: awk '$2=="'$var'"' /path/to/file (use single quotes, but interrupt the single quoted string where needed)
right: awk -v var=$var '$2==var' /path/to/file (use -v to preload an awk variable)



HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top