开发者_开发知识库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.
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.
comm -12 file1 file2
will show the lines common to both file1 and file2
#!/bin/sh
diff $1 $2
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.
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
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
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.
paste the code below into a file called intersect.sh
while read line
do
grep -n "^${line}$" $2;
done < $1
then make sure you have execute permissions on the file
chmod 777 intersect.sh
then run this command, substituting the names of your two files
./intersect.sh nameOfLongerFile nameOfShorterFile
精彩评论