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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With