Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two files and get the output for the same lines

Tags:

linux

bash

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. Thanks.

like image 244
garconcn Avatar asked May 14 '10 17:05

garconcn


People also ask

How do I find the common line between two files?

Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.

Which command shows the differences between two files line by line?

The Linux diff command is used to compare two files line by line and display the difference between them. This command-line utility lists changes you need to apply to make the files identical. Read on to learn more about the diff command and its options with easy-to-follow examples.

When two files are identical What is the output of diff command?

Explanation: When two files are identical, diff command does not produce any output. It simply returns the shell prompt $. However, we can use the -s option to display an informative message on the terminal if the files are identical.


3 Answers

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
like image 133
ire_and_curses Avatar answered Sep 28 '22 04:09

ire_and_curses


Use comm command.

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

This command is more accurate than grep -f.

like image 26
Antony.H Avatar answered Sep 28 '22 06:09

Antony.H


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
like image 39
jfg956 Avatar answered Sep 28 '22 05:09

jfg956