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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display/print only fields that contain string?

Status
Not open for further replies.

fixengineer

Technical User
Apr 5, 2007
19
US
Everything I read seems to deal with fixed amount of fields, but what if the amount of fields change? How can I search for a string in ALL fields(not a specific one like $1 $3) and display only that field?

If awk can't do it I'm thinking that maybe I can transfer the fields to positionals and then do a for loop that "ins" the positionals and checks if it matches a string, then stops once it finds the string and declares that the target field. There has to be an easier way though.

Thanks.
 
A starting point:
for(i=1;i<=NF;++i)if($i=="string")print $i

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
What is the context for your answer? Is this a for loop with an if then statement in it? AWK? Is there a way to do this with just awk and grep?
 
As you asked in the awk forum I posted an awk snippet.
 
By the way, another aproach on this would be using awk or sed to find a string and wildcard and then ONLY display what it finds or delete the rest of the line. Basically a grep -o alternative.

For message:

Frank^ATimmy^A4504

find ^ATim*^A(begin with "Tim" and end with "^A".

And display what you found/matched only:

Timmy^A
 
I was'nt sure if that was awk since it does not apear to follow the AWK syntax and I tried it and get this:

% cat -v fix.log | grep ABT1969 | awk for(i=1;i<=NF;++i)if($i=="string")print $i
bash: syntax error near unexpected token `for(i'

Where an how should I be using this?
 
awk '/ABT1969/{for(i=1;i<=NF;++i)if($i~/string/)print $i}' fix.log

You probably have to define the field separator.
You really search a field containing the literal [!]string[/!]
BTW, man awk is your friend.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
You are the man PHV!! That works like a charm! I just set the field seperator and bam! This is great! Being able to do this opens up MANY possibilities for me. Thank you VERY much!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top