从文件中获取模式,与另一个文件的列进行比较,打印匹配的行,使用 awk [英] Obtain patterns from a file, compare to a column of another file, print matching lines, using awk
问题描述
我基本上想结合
grep -f
与
awk '{ if($2=="this is where I'd like to input a file of fixed string patterns") print $0}'
也就是说,我想使用模式输入文件(文件 2)搜索文件(文件 1)的特定列.如果简单地找到匹配:
Which is to say, I'd like to search a specific column of a file (File 1) with an input file of patterns (File 2). If a match is found simply:
> outputfile.txt
从之前的帖子中,这条 awk 行非常接近:
From a previous post, this awk line is really close:
awk 'NR==FNR{a[$0]=1;next} {n=0;for(i in a){if($0~i){n=1}}} n' file1 file2
取自 使用 ack 或 awk 或比 grep 更好的方法从另一个文件中获取模式?
但它不会搜索文件 1 的特定列.我也可以使用其他工具.
But it doesn't search a specific column of file 1. I'm open to other tools as well.
推荐答案
你找到的例子确实很接近你想要的,唯一不同的是你不想匹配整行($0
).
The example you found is indeed very close to what you want, the only difference is that you don't want to match the whole line ($0
).
修改成这样:
awk 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($2 ~ p) { print $0; break } }' patterns file
如果你只需要一个固定的字符串匹配,使用 index()
函数代替,即将 $2 ~ p
替换为 index($2, p)代码>.
If you only need a fixed string match, use the index()
function instead, i.e. replace $2 ~ p
with index($2, p)
.
您还可以将列号作为参数提供给 awk,例如:
You could also provide the column number as an argument to awk, e.g.:
awk -v col=$col 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($col ~ p) { print $0; break } }' patterns file
编辑 - 整个字段匹配
您可以使用 ==
运算符来完成此操作:
Edit - whole field matching
You can accomplish this with the ==
operator:
awk -v col=$col 'NR==FNR { pats[$0]=1; next } { for(p in pats) if($col == p) { print $0; break } }' patterns file
这篇关于从文件中获取模式,与另一个文件的列进行比较,打印匹配的行,使用 awk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!