Cod*_*ezy 1 linux bash awk sed
现在我有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
Run Code Online (Sandbox Code Playgroud)
现在,我想删除第一列中包含file2中名称的行。
Ideal result:
john 12 65 0
lee 9 15 0
Run Code Online (Sandbox Code Playgroud)
谁能告诉我该怎么做?我已经尝试过这样的代码:
for i in 'less file2.txt'; do sed "/$i/d" file1.txt; done
Run Code Online (Sandbox Code Playgroud)
但是它不能正常工作。
该工作套件awk:
awk 'NR == FNR {a[$1]; next} !($1 in a)' file2.txt file1.txt
Run Code Online (Sandbox Code Playgroud)
john 12 65 0
lee 9 15 0
Run Code Online (Sandbox Code Playgroud)
细节:
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
Run Code Online (Sandbox Code Playgroud)
您无需对其进行迭代,只需使用带有-v选项的grep 即可将匹配反转并-w强制模式仅匹配整个单词
grep -wvf file2.txt file1.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |