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

Return field number of string in a line 1

Status
Not open for further replies.

stackdump

Technical User
Sep 21, 2004
278
GB
How do I determine which field a string is within a line?

e.g. "Hello how are you"

I want to find out the position of the word "how", which for this example is field 2.



 
You have to loop through all the fields until found
something like:

awk '{
for (i=1;i<=NF;i++) {
if ($i=="how") {
print
print "field number " i "is \"how\""
break
}
}
}' /path/to/inputfile


HTH,

p5wizard
 
ok, this more difficult than I first thought.

I'm processing a file that permits continuation lines. I need to extract the parameter after one that I know is definitely there.

a b c d KnownString TheValue e f

or it could be some combination like;
a b c d
+ KnownString
+ TheValue e
+ f

So I can match the line to see if KnownString is present. Then see if TheValue parameter is on the same line. If not look to the next line and take the second parameter.

Any help appreciated.

 
Code:
BEGIN { target = "KnownString" }

/^\+/ { sub( /^\+/, "" ); line = line $0 ; next }

{ process( line )
  line = $0
}
END { process( line ) }

function process( line )
{
  split( line, ary, /[ \t]+/ )
  for (i=1; i in ary; i++)
  { if (target == ary[i])
      print ary[i+1]
  }
}
 
Jeepers! Well your code is a lot shorter than the mess I've created so far! Thanks, have a star too.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top