bash 比较两个文件并获得相同行的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2836271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:06:19  来源:igfitidea点击:

compare two files and get the output for the same lines

linuxbash

提问by garconcn

How can I get the following output using linux command by comparing two text files? Thanks.

如何通过比较两个文本文件使用 linux 命令获得以下输出?谢谢。

file1:

文件 1:

site110
site120

file2(Updated):

文件 2(更新):

domain1.com - site110
domain2.com - site111
domain3.com - site112
domain4.com - site113
domain5.com - site120
domain6.com - site1201
domain7.com - site1202

output:

输出:

domain1.com - site110
domain5.com - site120

If I use:

如果我使用:

grep -f file1 file2

the output will be:

输出将是:

domain1.com - site110
domain5.com - site120
domain6.com - site1201
domain7.com - site1202

which the last two lines are not what I want. Thanks.

最后两行不是我想要的。谢谢。

回答by ire_and_curses

From the grep manpage:

grep 联机帮助页

   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.   The  empty file
          contains zero patterns, and therefore matches nothing.   (-f  is
          specified by POSIX.)

Therefore:

所以:

grep -f file1 file2

domain1.com - site110
domain5.com - site120

回答by Antony.H

Use commcommand.

使用comm命令。

comm -12 < (sort file1) < (sort file2)

This command is more accurate than grep -f.

此命令比grep -f.

回答by jfg956

I think you are looking for a kind of database join function. Unix has a command for that: join. In you case:

我认为您正在寻找一种数据库连接功能。Unix 有一个命令:join。在你的情况下:

join -1 1 -2 3 -t " " -o 2.1,2.2,2.3 file1 file2

回答by modz0r

How about diff?

差异怎么样?

回答by osgx

May be man paste? Some output processing can be needed.

可能是man paste?可能需要一些输出处理。