在 2 个集合/文件之间提取唯一值 [英] extracting unique values between 2 sets/files

查看:29
本文介绍了在 2 个集合/文件之间提取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 linux/shell env 中工作,我如何完成以下工作:

Working in linux/shell env, how can I accomplish the following:

文本文件 1 包含:

1
2
3
4
5

文本文件 2 包含:

6
7
1
2
3
4

我需要提取文件 2 中不在文件 1 中的条目.因此在本例中为6"和7".

I need to extract the entries in file 2 which are not in file 1. So '6' and '7' in this example.

如何从命令行执行此操作?

How do I do this from the command line?

非常感谢!

推荐答案

$ awk 'FNR==NR {a[$0]++; next} !($0 in a)' file1 file2
6
7

代码工作原理说明:

  • 如果我们正在处理 file1,请跟踪我们看到的每一行文本.
  • 如果我们正在处理 file2,并且没有看到行文本,则打印它.

细节说明:

  • FNR 是当前文件的记录号
  • NR 是所有输入文件的当前总记录号
  • FNR==NR 仅在我们读取 file1 时为真
  • $0 是当前文本行
  • a[$0] 是一个哈希,键设置为当前文本行
  • a[$0]++ 跟踪我们看到的当前文本行
  • !($0 in a) 只有当我们没有看到行文本时才为真
  • 如果上述模式返回 true,则打印文本行,这是未给出显式操作时的默认 awk 行为
  • FNR is the current file's record number
  • NR is the current overall record number from all input files
  • FNR==NR is true only when we are reading file1
  • $0 is the current line of text
  • a[$0] is a hash with the key set to the current line of text
  • a[$0]++ tracks that we've seen the current line of text
  • !($0 in a) is true only when we have not seen the line text
  • Print the line of text if the above pattern returns true, this is the default awk behavior when no explicit action is given

这篇关于在 2 个集合/文件之间提取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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