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?
Asked
Active
Viewed 4,163 times
12
Gilles 'SO- stop being evil'
- 807,993
- 194
- 1,674
- 2,175
Martijn Burger
- 225
- 2
- 8
3 Answers
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
-
2Note that it would answer "the same" if file1 is an empty file (or not readable) and file2's first line is empty. – Stéphane Chazelas Apr 23 '15 at 12:54
-
I did not say that this method is 'idiot proof' but if you quickly want to match the first line of two files... – Lambert Apr 23 '15 at 12:58