08. Comparing Text cmp, comm

Comparing bytes with cmp

The cmp command compares files byte by byte. Use the -b option to see where the first difference occurs.

$ cat file1.txt
hello how are you?
$ cat file2.txt
hello how art thee?
$ cmp -b file1.txt file2.txt
file1.txt file2.txt differ: byte 13, line 1 is 145 e 164 t

You may skip the first n bytes with the -i option. Or to compare at most n bytes, use the -n option.

Comparing lines with comm

The comm command allows you to see the lines common to two files. Simply pass in the file names of the two files you'd like to compare.

Let's first take a look at the two files we will use as an example:

$ cat file1.txt
Humphrey: Hey what's up? Jen: I'm fine how are you? Humphrey: I'm find as well. Jen: Great - want to watch a movie some time?
$ cat file2.txt
Humphrey: Top of the mornin' to ya - how art thee? Jen: I'm fine how are you? Humphrey: Thy is fine as one can be. Jen: Great - I'll see you around!

There are three columns of output that gets generated. The first column is indented by one tab, the second, two tabs, the third, three.

The first column shows the lines that are unique to the first file, while the second are those unique to the second file. The third line shows the line numbers that the files have in common.

$ comm file1.txt file2.txt
Humphrey: Hey what's up? Humphrey: Top of the mornin' to ya - how art thee? Jen: I'm fine how are you? Humphrey: I'm find as well. Humphrey: Thy is fine as one can be. Jen: Great - I'll see you around! Jen: Great - want to watch a movie some time?

To suppress any of these columns, use the -n option where n specifies the column number.

$ comm -12 file1.txt file2.txt
# Print only column 3 - lines that the files have in common
Jen: I'm fine how are you?

Case-insensitive

Use the -i option for a case-insensitive comparison.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

The Linux Command Line

Take your Linux skills to the next level! Try Linux & UNIX

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Ad