Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

.

a
3
4
share|improve this question
    
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

1 Answer 1

up vote 5 down vote accepted

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

share|improve this answer
    
+1 Good use of process substitution. –  Nicole Hamilton Nov 27 '12 at 17:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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