Search code examples
pythonlinuxbashperlterminal

How to compare 2 files line by line with terminal


I have 2 text files that I need to compare line by line.

I'm basically wanting to output either "matching" or "not matching" for each line depending on if it matches.

I've tried reading a few tutorial and using stuff like diff and dircmp but can't seem to find a way to do this. I don't care if it's bash, perl, python, etc. Both files are 243 lines.

Is there a command available in Linux to do this?

Here's an example of what I'm looking for...

File 1

Test
Hello
Example

File 2

Test
What
Example

And I'd want to output this:

matching
not matching
matching

Solution

  • What you are after is an awk script of the following form:

    $ awk '(NR==FNR){a[FNR]=$0;next}
           !(FNR in a) { print "file2 has more lines than file1"; exit 1 }
           { print (($0 == a[FNR]) ? "matching" : "not matching") }
           END { if (NR-FNR > FNR) print "file1 has more lines than file2"; exit 1}' file1 file2