Grep精确匹配字符串,其中空格为变量 [英] Grep exact match string with spaces as variable
本文介绍了Grep精确匹配字符串,其中空格为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
file.csv
其中包含
2,1,"string with spaces",3,4,5
2,1,"some other string",3,4,5
2,1,"string with spaces more than this",3,4,5
2,1,"yet another",3,4,5
2,1,"string with spaces too",3,4,5
当我这样做时:
grep '"string with spaces",' file.csv
它产生想要的结果:
2,1,"string with spaces",3,4,5
现在我需要在while循环中这样做:
Now I need to do this in a while loop:
while read p; do
grep '"$p",' file.csv
done < list.txt
位置:
list.txt
包含:
string with spaces
yet another
我想要的输出是:
2,1,"string with spaces",3,4,5
2,1,"yet another",3,4,5
问题是我的while循环返回为空或部分匹配.如何遍历list.txt
&得到我想要的输出?
The problem is that my while loop comes back empty, or matches partially. How do I loop through list.txt
& get my desired output?
推荐答案
如果您对awk
没问题,那么这应该很简单.
If you are ok with awk
this should be an easy one for it.
awk 'FNR==NR{a[$0];next} ($4 in a)' list.txt FS="[,\"]" file.csv
OR(根据Ed ir先生的评论,将字段分隔符设置为逗号并保持更清晰,可以尝试跟随)
OR(as per Ed sir's comment to make field separator as comma and keep it clearer, one could try following)
awk -F, 'FNR==NR{a["\""$0"\""];next} $3 in a' list.txt file.csv
输出如下.
2,1,"string with spaces",3,4,5
2,1,"yet another",3,4,5
这篇关于Grep精确匹配字符串,其中空格为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文