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