Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through fields in awk

Tags:

sed

awk

Suppose I have the following three lines in a text file:

I have a dog 
The dog is goood
The cat runs well

Now I need to go through the file. And print the lines where the word dog occurs along with the field no in which it occurs. I need to accomplish this through awk.

Is there any way by which while processing a line I can sequentially increase the field number, something like the following:

more abc.txt | awk ' j = $NF for (i =1 ; i<= j ; ++i) if ( $N$i == "dog") n= $N0" "$i '

How to loop through the fields of a line in awk?

like image 613
awkward sedist Avatar asked Apr 21 '18 21:04

awkward sedist


3 Answers

awk '{for(i=1; i<=NF; i++) {if($i=="dog") print $0,i}}' file

Output:

I have a dog 4
The dog is goood 2

I assume that each line contains the searched string only once.

like image 197
Cyrus Avatar answered Jan 23 '23 04:01

Cyrus


Solution:

awk '/dog/ {for(i=NF;i>=1;i--) {if($i~/dog/) {$0=i":"$0}} print}' file

Input file:

I have a dog 
The dog is a good doggie
The cat runs well

Output:

4:I have a dog 
2:6:The dog is a good doggie

Features:

  • First checks whether the line contains the desired text before cycling through the fields (although I don't think this provides much of a speedup)

  • Not only finds fields that are identical to the desired text, but also fields that contain it

  • Prints the field number of all fields in the line that match the desired text

like image 37
simlev Avatar answered Jan 23 '23 04:01

simlev


$NF holds last field value, i is a number and $i refers to a field value on that number. $N$i means field number 0 (which is whole line, since N isn't initialized) concatenated to value of field number i. You are doing almost every thing wrong. Try:

more abc.txt | awk '{for (i =1; i<=NF ; i++) if ($i == "dog") print $0 i}'
like image 37
revo Avatar answered Jan 23 '23 05:01

revo