Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which line is missing in another file

Tags:

linux

grep

sed

awk

on Linux box I have one file as below A.txt

1
2
3
4

Second file as below B.txt

1
2
3
6

I want to know what is inside A.txt but not in B.txt i.e. it should print value 4

I want to do that on Linux.

like image 776
user3190479 Avatar asked Jan 17 '14 14:01

user3190479


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.

How do we display the last second line of a file?

To look at the last few lines of a file, use the tail command.

How do I see all lines in a file in Linux?

The simplest way to view text files in Linux is the cat command. It displays the complete contents in the command line without using inputs to scroll through it. Here is an example of using the cat command to view the Linux version by displaying the contents of the /proc/version file.

How do I count the number of lines in a file without opening the file in Linux?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.


2 Answers

You can also do this using grep by combining the -v (show non-matching lines), -x (match whole lines) and -f (read patterns from file) options:

$ grep -v -x -f B.txt A.txt
4

This does not depend on the order of the files - it will remove any lines from A that match a line in B.

like image 185
rjmunro Avatar answered Sep 17 '22 00:09

rjmunro


awk 'NR==FNR{a[$0]=1;next}!a[$0]' B A

didn't test, give it a try

like image 32
Kent Avatar answered Sep 21 '22 00:09

Kent