现在我有2个文件,如下所示:
>cat file1.txt
john 12 65 0
Nico 3 5 1
king 9 5 2
lee 9 15 0
>cat file2.txt
Nico
king
现在,我想删除第一列中包含file2中名称的行。
Ideal result:
john 12 65 0
lee 9 15 0
谁能告诉我该怎么做?我已经尝试过这样的代码:
for i in 'less file2.txt'; do sed "/$i/d" file1.txt; done
但是它不能正常工作。
答案 0 :(得分:5)
您不需要进行迭代,只需要使用带有-v
选项的grep即可将匹配反转,而-w
则可以强制模式仅匹配整个单词
grep -wvf file2.txt file1.txt
答案 1 :(得分:3)
此工作套件awk
:
awk 'NR == FNR {a[$1]; next} !($1 in a)' file2.txt file1.txt
john 12 65 0
lee 9 15 0
详细信息:
NR == FNR { # While processing the first file
a[$1] # store the first field in an array a
next # move to next line
}
!($1 in a) # while processing the second file
# if first field doesn't exist in array a then print