Reputation: 411
I am doing a file traversal in awk. An example of this is
Dat time range column session - 1
time name place session animal - 2
hi bye name things - 3
In both of these . I need to traverse line by line and in I need to traverse word by word in the line that contains session
.
Thus in this case I need to reach line 1 and 2 as it contains the word session and not line 3 as it doesn't contain that field(In the sense I can skip this). From there I need to traverse word by word to reach the session field .
I know $0
can represent the whole line. But my question is how to traverse word by word after reaching the line.
Could you please help me regarding this. Thank you.
Upvotes: 0
Views: 398
Reputation: 47503
You can use a for
loop, filtering only on the lines that contain "session":
awk '/session/{ for (i = 1; i <= NF; i++) { \
if ($i == "session") \
do_whatever_here \
} \
}'
You can read more on these instructions here: for
, string comparison and if
.
Upvotes: 1
Reputation: 143047
You can loop through the current line $0
with this construct:
for(i = 1; i <= NF; i++) print $i
this makes use of the predefined awk variable NF
which stands for the number of fields on the current line ($0
).
You can examine the value of $i
as it iterates through the line and based on that determine what to do with the value. E.g, print it, skip it, etc. if ($i == "session") ...
Update:
You can also use the match()
function to determine if the current line you are processing contains the "session" string without iterating through the line. E.g.,
where = match($0, "session")
if (where > 0)
print "Found session in this line";
else
print "session not found in this line";
Note that match()
takes a regular expression as the 2nd parameter, so your matches can be quite sophisticated. See this page for more information about this function and other awk string functions.
Upvotes: 1