AWK搜索事实本身在同一个文件中

时间:2015-11-09 20:03:35

标签: linux bash awk

我有一个文件

数据是

90|123456|.. some more fields
90|654321|... some more fields
.... some more lines starting with 90
91|123456|.. some more fields
91|654321|... some more fields
.... some more lines starting with 91
92|123456|.. some more fields
92|654321|... some more fields
.... some more lines starting with 92

第二场是我的关键价值 &安培;它将有90,91&起始字段中的92个值

90|keyvalue will always be there
91|keyvalue .. not mendatory
92|keyvalue .. not mendatory

预期产出

90|keyvalue [Mendatory]
91|keyvalue --> print if exist in file
92|keyvalue --> print if exist in file

表示所有键值

我做的是

grep "^90" origfilename |awk -F '|' '{print $2}'> temp90.txt #this gives me all keyvalues

awk '{print "90|"$0"|"}' temp90.txt >> temp90-1.txt
awk '{print "91|"$0"|"}' temp90.txt >> temp90-1.txt
awk '{print "92|"$0"|"}' temp90.txt >> temp90-1.txt

grep -f temp90-1.txt origfilename

这让我得到了输出但我认为这不是正确有效的方法来做到这一点

如何在单个awk或其他方式上执行此操作

1 个答案:

答案 0 :(得分:3)

awk救援!

$ awk -F'|' 'NR==FNR && /^90/  {k[$2]} 
             NR!=FNR && $2 in k{print}' file{,}

90|123456|.. some more fields
90|654321|... some more fields
91|123456|.. some more fields
91|654321|... some more fields
92|123456|.. some more fields
92|654321|... some more fields

说明在第一次扫描中获取键,在第二次扫描中使用匹配键打印行。请注意,file{,}file file的{​​{1}}相同,可以对输入文件进行双重扫描。