BASH-如果第一列内容出现在另一个文件中,则删除行 [英] BASH - remove line if first column content appears in another file

查看:104
本文介绍了BASH-如果第一列内容出现在另一个文件中,则删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个文件.文件A如下:

If I have two files. File A looks like:

a 1
a 2
a 3
b 4
c 5

我有文件B,其中包含内容:

and I have file B which has content:

a
b

对于文件B中出现的所有内容,以及文件A中第1列中出现的所有内容,我想删除这些行.因此,文件A的预期输出应为:

For everything that appears in file B and also appears in column 1 in file A, I would like to remove those lines. So the expected output for file A should be:

c 5

任何帮助将不胜感激!

推荐答案

GNU Awk:

awk 'ARGIND == 1 { del[$0]++ } ARGIND == 2 && !del[$1]' B A

在处理第一个文件(ARGIND为1)时,通过增加其条目将$0(每一行)输入到关联数组del中.

When processing the first file (ARGIND is 1), enter $0 (each entire line) into an associative array del by incrementing its entry.

在处理第二个文件时,如果第一个字段$1del中的非零计数没有关联,则打印.

When processing the second file, print if the first field $1 is not associated with a nonzero count in del.

当然,我们将B作为第一个文件,并将A作为第二个文件.

Of course, we make B the first file and A second.

(当ARGIND == 2 && !del[$1]模式表达式产生布尔值true时,打印操作是隐式的.没有操作的模式具有与{ print }等效的隐式操作).

(The printing action is implicit when the ARGIND == 2 && !del[$1] pattern expression yields a Boolean true. A pattern without an action has an implict action equivalent to { print }).

ARGIND不在POSIX中.在可移植的Awk代码中,可能会使用丑陋的方法来区分第一个文件和第二个文件:

ARGIND is not in POSIX. In portable Awk code, an ugly hack may be used to distinguish the first file from the second:

awk 'FNR == NR { del[$0]++ } FNR < NR && !del[$1]' B A

处理第一个文件时,文件记录号"(当前文件中的记录号)等于总记录号"(所有文件中处理的绝对记录号).当然,如果第一个文件根本不包含任何记录,则此操作会中断.参见什么是"NR == FNR";在awk中?

When the first file is processed, the "file record number" (record number in the current file) is equal to the "total record number" (absolute record number processed across all files). Of course, this breaks if the first file contains no records at all. See What is "NR==FNR" in awk?

这篇关于BASH-如果第一列内容出现在另一个文件中,则删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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