开发者

compare two files and get the output for the same lines

开发者 https://www.devze.com 2022-12-30 13:14 出处:网络
How can I get the following output using linux command by comparing two text files? Thanks. file1: site110

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

file1:

site110
site120

file2(Updated):

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开发者_Go百科. Thanks.


From the grep manpage:

   -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


Use comm command.

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

This command is more accurate than grep -f.


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

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


How about diff?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消