How to diff only the first line of two files?

Solution 1:

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 <(...) <(...)'