views:

216

answers:

7

how could we compare lines in two files using a shell script.

I want to compare line in one file with the line in other.diff will give me all the differences in two files at a time.i want a line in the first file to be compared with all the lines in the second file and get the common lines as the output. with the line numbers where the lines are present in the second file.

+1  A: 
#!/bin/sh
diff $1 $2
Jonathan Feinberg
I want to compare line one file with the other.diff will give me all the differences in two files at a time.i want a line in the first file to be compared with all the lines in the second file and get the common lines as the output. with the line numbers where the lines are present in the second file.
Vijay Sarathi
It would have been good to say so in your question.
Jonathan Feinberg
+2  A: 

I am not sure exactly what you are asking, but how about:

grep -n -v "`head -1 FILE1`" FILE2

This will give you the numbered lines in FILE2 that do not contain the 1st line in FILE1.

rsp
Or omit the `-v` if you want the lines that match the first line from FILE1.
steveha
A: 

grep -n is the tool to use in your case. As the pattern, you put the line in the first file that you want to find in the second one. Make your pattern start with ^ and end with $ and put quotes around it.

mouviciel
A: 

I want to compare line one file with the other.diff will give me all the differences in two files at a time.i want a line in the first file to be compared with all the lines in the second file and get the common lines as the output. with the line numbers where the lines are present in the second file

I think this gets close.

#!/bin/sh
REF='a.txt'
TARGET='b.txt'

cat $REF | while read line
do
  echo "line: $line"
  echo '==========='
  grep -n $line $TARGET
done
Ewan Todd
A: 

This is not elegant at all, but it is simple

let filea be:

foo
bar
baz
qux
xyz
abc

and fileb be:

aaa
bar
bbb
baz
qux
xxx
foo

Then:

while read a ; do
  grep -n "^${a}$" fileb ;
done < filea

Will output:

7:foo
2:bar
4:baz
5:qux
Chen Levy
You've now done his homework for him.
Jonathan Feinberg
A: 

you can use comm command to compare 2 files which gives the output in a SET operations format like a - b, a intersection b etc.

this gives the common lines in both files. comm -12 <(sort first.txt | uniq) <(sort second.txt | uniq)

Syntax comm [options]... File1 File2

Options -1 suppress lines unique to file1 -2 suppress lines unique to file2 -3 suppress lines that appear in both files

A file name of `-' means standard input.

Venkataramesh Kommoju
A: 
comm -12 file1 file2

will show the lines common to both file1 and file2

Nick Dixon