Bash 比较2个csv文件并删除行-Shell
我有两个csv文件。一个有多个列,另一个只有一个带域的列。这些文件的简化数据将是 file1.csv:Bash 比较2个csv文件并删除行-Shell,bash,shell,Bash,Shell,我有两个csv文件。一个有多个列,另一个只有一个带域的列。这些文件的简化数据将是 file1.csv: John,example.org,MyCompany,Australia Lenny,domain.com,OtherCompany,US Martha,site.com,ThirdCompany,US file2.csv: example.org google.es mysite.uk 输出应该是 Lenny,domain.com,OtherCompany,US Martha,site.
John,example.org,MyCompany,Australia
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
file2.csv:
example.org
google.es
mysite.uk
输出应该是
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
我尝试过这个解决方案
grep-v-f file2.csv file1.csv>输出文件
在这里找到
但是,由于没有任何关于脚本如何工作的解释,而且我对shell很差劲,所以我无法调整它使其适合我
对此的解决方案将不胜感激,一个有一些解释的解决方案将非常棒!:)
编辑:
我已经试过那条本该行得通的路线,但不知为什么不行。这里是我终端的输出。这个怎么了
Desktop $ cat file1.csv ; echo
John,example.org,MyCompany,Australia
Lenny ,domain.com,OtherCompany,US
Martha,mysite.com,ThirCompany,US
Desktop $ cat file2.csv ; echo
example.org
google.es
mysite.uk
Desktop $ grep -v -f file2.csv file1.csv
John,example.org,MyCompany,Australia
Lenny ,domain.com,OtherCompany,US
Martha,mysite.com,ThirCompany,US
为什么grep
不删除该行
John,example.org,MyCompany,Australia
awk中的一个:
$ awk -F, 'NR==FNR{a[$1];next}($2 in a==0)' file2 file1
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
解释:
$ awk -F, ' # using awk, comma-separated records
NR==FNR { # process the first file, file2
a[$1] # hash the domain to a
next # proceed to next record
}
($2 in a==0) # process file1, if domain in $2 not in a, print the record
' file2 file1 # file order is important
你发的那条线,效果很好
$ grep -v -f file2.csv file1.csv
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
这里有一个解释。将在给定文件中搜索给定图案并打印所有匹配的行。最简单的用法示例是:
$ grep John file1.csv
John,example.org,MyCompany,Australia
在这里,我们使用了一个匹配每个字符的简单模式,但也可以使用正则表达式(基本、扩展,甚至与perl兼容的正则表达式)
要反转逻辑并仅打印不匹配的行,我们使用-v
开关,如下所示:
$ grep -v John file1.csv
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
$ grep -v -e John -e Lenny file1.csv
Martha,site.com,ThirdCompany,US
要指定多个图案,可以多次使用选项-e pattern
,如下所示:
$ grep -v John file1.csv
Lenny,domain.com,OtherCompany,US
Martha,site.com,ThirdCompany,US
$ grep -v -e John -e Lenny file1.csv
Martha,site.com,ThirdCompany,US
但是,如果要检查的模式数量较多,我们可以使用-f file
选项,该选项将从指定的文件中读取所有模式
所以,当我们把所有这些结合起来;使用-f
读取文件中的模式,并使用-v
反转匹配逻辑,我们可以得到您需要的行。为什么mysite.uk
会匹配最后一行的site.com
?TLD
是否不构成字符串匹配的一部分?此grep-v-f file2.csv file1.csv
与输入文件配合良好