我正在从文件 appliances_list.txt 中读取一个字符串。
appliances_list.txt 包含
fridge
dryer
ironbox
microwave
我正在阅读的文件是 myappliances.txt。内容是
I have a fridge
I have another fridge
I have a refridgerator
I have a microwave
I have ironbox at home
I have another microwave
I have a hairdryer
我在用
grep -o -m1 -f appliances_list.txt myappliances.txt
输出是
冰箱
我想要的输出是每个字符串的第一次出现(完全匹配)
fridge
microwave
ironbox
有人能指出我正确的方向吗?
最佳答案
$ cat tst.awk
NR==FNR { strings[$0]; ++numStrings; next }
{
for (i=1;i<=NF;i++) {
if ($i in strings) {
print $i
delete strings[$i]
if (--numStrings == 0) {
exit
}
break
}
}
}
$ awk -f tst.awk appliances_list.txt myappliances.txt
fridge
microwave
ironbox
这将非常有效,因为它会在找到字符串列表时从字符串列表中删除每个找到的字符串,因此每一行都需要进行较少的比较,并且当列表中没有更多字符串时将退出程序,因此不会浪费阅读第二个文件的剩余行的时间。
关于linux - 从一个文件中读取字符串,grep 在另一个文件中第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45985910/