从另一个文件中减去一个文件中的行 [英] Subtracting lines in one file from another file

查看:72
本文介绍了从另一个文件中减去一个文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到真正从另一个文件中减去一个文件的答案.

I couldn't find an answer that truly subtracts one file from another.

我的目标是删除一个文件中出现在另一文件中的行. 应该考虑多次出现,这意味着,例如,如果文件A中出现了4行,而文件B中仅出现了1行,则文件C应该具有其中的3行.

My goal is to remove lines in one file that occur in another file. Multiple occurences should be respected, which means for exammple if one line occurs 4 times in file A and only once in file B, file C should have 3 of those lines.

文件A:

1
3
3
3
4
4

文件B:

1
3
4

文件C(所需输出)

3
3
4

预先感谢

推荐答案

在awk中:

$ awk 'NR==FNR{a[$0]--;next} ($0 in a) && ++a[$0] > 0' f2 f1
3
3
4

解释:

NR==FNR {                  # for each record in the first file
    a[$0]--;               # for each identical value, decrement a[value] (of 0)
    next
} 
($0 in a) && ++a[$0] > 0'  # if record in a, increment a[value]
                           # once over remove count in first file, output

如果要在f1中打印不在f2中的项目,则可能会丢失($0 in a) &&:

If you want to print items in f1 that are not in f2 you can lose ($0 in a) &&:

$ echo 5 >> f1
$ awk 'NR==FNR{a[$0]--;next} (++a[$0] > 0)' f2 f1
3
3
4
5

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

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