27

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:

a
1
2

and:

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

2 Answers 2

43

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)

Returns:
2c2
< 1
---
> 3

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

#!/bin/bash

fileOne=${1}
fileTwo=${2}
numLines=${3:-"1"}

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 <(...) <(...)'
10
  • How would that work for recursive diff when I need to diff two directories?
    – lanoxx
    Commented Oct 2, 2015 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
    Commented Oct 2, 2015 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
    Commented Oct 4, 2015 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
    Commented Oct 4, 2015 at 16:09
  • 1
    @Veridian What shell are you using? This is bash specific, so you may need to call bash -c "diff <(...) <(...)"
    – nerdwaller
    Commented May 10, 2016 at 19:20
-2

diff -U (n of lines) file1 file2

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .