【问题标题】:How to remove lines based on another file? [duplicate]如何删除基于另一个文件的行? [复制]
【发布时间】:2019-11-24 01:31:00
【问题描述】:

现在我有两个文件如下:

$ cat file1.txt
john  12  65  0
Nico  3   5   1
king  9   5   2
lee   9   15  0

$ cat file2.txt
Nico
king

现在我想从第二个文件的第一列中删除包含名称的每一行。

理想结果:

john  12  65  0
lee   9   15  0

谁能告诉我该怎么做?我试过这样的代码:

for i in 'less file2.txt'; do sed "/$i/d" file1.txt; done

但它不能正常工作。

【问题讨论】:

标签: linux bash awk sed


【解决方案1】:

你不需要迭代它,你只需要使用 grep with-v 选项来反转匹配和-w 强制模式只匹配整个单词

grep -wvf file2.txt file1.txt

【讨论】:

  • 这将给出不正确的结果,因为它可能匹配部分单词。例如如果第一个文件的名称以kingsley 开头,则此命令也不会显示该名称。
  • 这可以通过-w 选项来缓解。并且可能还想添加-F
  • @anubhava 感谢您指出这一点,使用 -w 选项,我们可以像 glenn 所说的那样解决这个问题。更新了答案
【解决方案2】:

这份工作适合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

【讨论】:

  • 非常感谢 :) 我会接受它作为答案。你能解释一下你的代码吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多