与环一起awk脚本 [英] awk script along with for loop
问题描述
我有一个数据集 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
我也有一个第二个文件 t1.txt
:
752
728
856
693
713
792
812
706
737
751
745
我试图从数据中提取组对应列第二档顺序的2个元素。
我用:的awk -F,'$ 1 == 752 {打印$ 2}'t.txt>> t2.txt
我如何可以使用for循环上述指令和一个在一个文本文件中填充它,而不是做一个?
有关752输出将是694.这694应在不同的文本文件写入。为812,它应该给我820两者694和820应在相同的文本文件被写入。它应该解析直到输入文件的末尾。
我尝试:
为我在'猫t1.txt` | awk的-F,'$ 1 == $ I {打印$ 2}'t.txt>> t2.txt
这是扔语法错误。
回答这个问题第三版
$ AWK'FNR == {NR一个[$ 1] = 1;下一个;} $ 1的打印{$ 2;}'t1.txt t.txt
694
820
774
回答这一问题的第二个版本
对于 t1.txt
的每一行,这个检查是否同一号码显示在任的第1列 t.txt
。如果确实如此,在同一行的2列中的数字被印刷
$ AWK'FNR == {NR一个[$ 1 = $ 2;接下来} $ 1的{打印[$ 1]}'t.txt t1.txt
694
820
要保存的文件输出 t2.txt
,使用:
的awk'FNR == {NR一个[$ 1 = $ 2;接下来} $ 1的{打印[$ 1]}'t.txt> t2.txt
工作原理
-
FNR == {NR一个[$ 1 = $ 2;接下来}
这通过读取
t.txt
,并创建一个数组A
其价值的。 -
$ 1的{打印[$ 1]}
有关文件中的每个号码
t1.txt
,这个检查,看是否号码出现在阵A
和如果是这样,打印出相应的值。
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.
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 arraya
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 arraya
and, if so, prints out the corresponding value.
这篇关于与环一起awk脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!