I want to diff only the first line of two files, as opposed to the entire file. How would I do that? I only need a solution for the the first line, but if you could specify the number of lines that would be a much better answer.

So diff would return no differences between the following two files:



  • did that work for you...?
    – nerdwaller
    Nov 28 '12 at 21:05
  • @nerdwaller Yup, accepted.
    – gsingh2011
    Nov 29 '12 at 3:58
  • cool beans. Was trying to think of other options, fortunately that's not necessary.
    – nerdwaller
    Nov 29 '12 at 4:13

Here you go:

diff <(head -n 1 file1) <(head -n 1 file2)

(this would return nothing what-so-ever).

diff <(head -n 2 file1) <(head -n 2 file2)

< 1
> 3

You could incorporate that into a script to do the things you mention.



diff <(head -n ${numLines} ${fileOne}) <(head -n ${numLines} ${fileTwo})

To use that, just make the script executable with chmod +x nameofscript.sh and then to execute, ./nameofscript.sh ~/file1 ~/Docs/file2 That leaves the default # of lines at 1, if you want more append a number to the end of that command.

(Or you could do switches in your script with -f1 file1 -f2 file2 -n 1, but I don't recall of the top of my head the case statement for that).

head returns from the beginning the # of lines as suggested by -n. If you were to want to do reverse, it would be tail -n ${numLines} (tail does from the end back the number of lines).

Edit 5/10/16:

This is specific to Bash (and compatible shells). If you need to use this from something else:

bash -c 'diff <(...) <(...)'
  • How would that work for recursive diff when I need to diff two directories?
    – lanoxx
    Oct 2 '15 at 10:16
  • @lanoxx diff -r dir1 dir2 for directories, to limit it you'll probably want to pipe that to something else. If you have specifics open a new question and give a link here.
    – nerdwaller
    Oct 2 '15 at 15:08
  • Well basically the same question just recursively: Diff only ( the first n lines | everything except the first n lines) for for all files in two directories.
    – lanoxx
    Oct 4 '15 at 16:07
  • @lanoxx like I said, make a new question and link it. It's best practice for the super user community instead of expanding the scope of some other user's question.
    – nerdwaller
    Oct 4 '15 at 16:09
  • 1
    @Veridian What shell are you using? This is bash specific, so you may need to call bash -c "diff <(...) <(...)"
    – nerdwaller
    May 10 '16 at 19:20

diff -U (n of lines) file1 file2

  • 1
    Welcome to Super User! Can you elaborate a little on the -U argument? :)
    – bertieb
    Apr 16 '18 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.