Sujay Shalawadi
Sujay Shalawadi

Reputation: 101

awk script along with for loop

I have a data set t.txt:

827 819
830 826
828 752
752 694
828 728
821 701
724 708
826 842
719 713
764 783
812 820
829 696
697 849
840 803
752 774

I also have a second file t1.txt:

752
728
856
693
713
792
812
706
737
751
745

I am trying to extract corresponding column 2 elements of the second file sequentially from the data set.

I have used: awk -F " " '$1==752 {print $2}' t.txt >> t2.txt

How can i use for loop for the above instruction and populate it in one text file instead of doing it one by one?

output for 752 will be 694. This 694 should be written in a different text file. For 812, it should give me 820. Both 694 and 820 should be written in the same text file. It should parse till end of the input file.

I was trying :

for i in `cat t1.txt` | awk -F " "  '$1==$i {print $2}' t.txt >> t2.txt 

which is throwing syntax error.

Upvotes: 2

Views: 89

Answers (1)

John1024
John1024

Reputation: 113844

Answer for 3rd Version of This Question

$ awk 'FNR==NR{a[$1]=1;next;} $1 in a {print $2;}' t1.txt t.txt
694
820
774

Answer for 2nd Version of This Question

For every line in t1.txt, this checks to see if the same number appears in either column 1 of t.txt. If it does, the number in column 2 of the same line is printed:

$ awk 'FNR==NR{a[$1]=$2;next} $1 in a {print a[$1]}' t.txt t1.txt
694
820

To save the output in file t2.txt, use:

awk 'FNR==NR{a[$1]=$2;next} $1 in a {print a[$1]}' t.txt >t2.txt

How it works

  • FNR==NR{a[$1]=$2;next}

    This reads through t.txt and creates an array a of its values.

  • $1 in a {print a[$1]}

    For each number in file t1.txt, this checks to see if the number appears in array a and, if so, prints out the corresponding value.

Upvotes: 5

Related Questions