12

I can do diff filea fileb to see the difference between files. I can also do head -1 filea to see the first line of filea or fileb. How can I combine these commands to show the difference between the first line of filea and the first line of fileb?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Martijn Burger
  • 225
  • 2
  • 8

3 Answers3

23

If your shell supports process substitution, try:

diff <(head -n 1 filea) <(head -n 1 fileb)
cuonglm
  • 150,973
  • 38
  • 327
  • 406
  • I had already seen the process substition command somewhere, but didn't know what it did. Thanks ! – edi9999 Apr 23 '15 at 14:47
6

If you are only comparing the first line of each file, maybe you care about word-level changes within the line, using dwdiff:

dwdiff <(head -n 1 filea) <(head -n 1 fileb)

dwdiff has some nice options, like -c to colorize the changed words.

Or, using sed instead of head:

dwdiff <(sed 1q filea) <(sed 1q fileb)

which the manual for head suggests is more portable than head, as the syntax for head has changed over time head -1 vs head -n 1

Also, you could just eyeball the changes, with a bit less typing:

head -n1 -q filea fileb

which displays the two lines, one below the other, for easy visual comparison.

James Scriven
  • 434
  • 3
  • 10
0

You can use:

if [ "`head -1 file1`" == "`head -1 file2`" ]; then echo "the same"; fi
Lambert
  • 12,495
  • 2
  • 26
  • 35