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!

USING AWK TO SEARCH AND PRINT FIELDS

Status
Not open for further replies.

johngiggs

Technical User
Oct 30, 2002
492
US
I use nawk to search for a string in a particular field and then print that particular field, however if for some reason, the string I want to print is in the next field, it will not print it.

Ex. cat file | nawk '$5 ~ /TEST/{print $5, $6}'

This works fine when TEST is in the 5th field, however if TEST appears in the 6th field, I would like to print the 6th and 7th fields.

How can I use awk to do this?

Any help would be greatly appreciated.

Thanks,

John
 
How about this:
for (i=5 ; i < NF ; i++) {
if ($i ~ /TEST/) {
print $i, $(i + 1)
}
}
 
my version:

/TEST/{ # found TEST, which field contains it ?
for(iii = NF; $iii !~ /TEST/; --iii);
print $iii, $(iii+1);
next; # not really needed, but for clarity
}
#PS: NOT TESTED
#PPS: i don't like variable names like 'i'
# how do you changes that 'i' to 'iii'
# in a xTousend-lines code file ?
 
$5 ~ /TEST/ {print $5, $6}
$5 !~ /TEST/ && $6 ~ /TEST/ {print $6, $7}
#Not really clear on the problem: specific (like this), or general?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top