如何删除基于另一个文件的行? [英] How to remove lines based on another file?

查看:65
本文介绍了如何删除基于另一个文件的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有两个文件,如下所示:

Now I have two files as follows:

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

$ cat file2.txt
Nico
king

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

Now I would like to remove each line which contains a name fron the second file in its first column.

理想的结果:

john  12  65  0
lee   9   15  0

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

Could anyone tell me how to do that? I have tried the code like this:

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

但是它不能正常工作.

推荐答案

此作业套件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

这篇关于如何删除基于另一个文件的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆