重要的是要知道它们keys
是独一无二的。因此,如果您打算将搜索模式存储为键并将行号存储为值,那么值将被看到模式的最后一行覆盖。
所以一个很好的方法是:
awk '{a[NR]=$1} END {for (k in a) if(a[k]=="monkey") print k}' textile
输出:
[jaypal:~] cat textfile
monkey
donkey
apple
monkey
dog
cat
mat
horse
monkey
[jaypal:~] awk '{a[NR]=$1} END {for (k in a) if(a[k]=="monkey") print k}' textfile
4
9
1
如果您需要遍历行以查找特定模式并将其存储,那么您可以使用for loop
检查行中的每个单词,一旦找到您的单词,将其存储为数组。
awk '{ for (i=1;i<=NF;i++) if($i=="pattern") arry[NR]=$i } END {. . .}' inputfile
根据评论更新:
迭代两个文件(其中一个用作查找,第二个用于搜索匹配查找的行)。
awk 'NR==FNR{a[NR]=$1; next} {for (x in a) if ($0 ~ a[x]) print $0 " found because of --> " a[x]}' textile text2
测试:
[jaypal:~] cat text2
monkeydeal
nodeal
apple is a good fruit
[jaypal:~] awk 'NR==FNR{a[NR]=$1; next} { for (x in a) if ($0 ~ a[x]) print $0 " found on line number " FNR " because of --> " a[x]}' textfile text2
it is a good monkeydeal found on line number 1 because of --> monkey
it is a good monkeydeal found on line number 1 because of --> monkey
it is a good monkeydeal found on line number 1 because of --> monkey
apple is a good fruit found on line number 3 because of --> apple