Here I want to discuss the command or single liners for finding the words
common in two given text files or their difference .Difference what mean here is that such words which are present in one file but not in other just analogous to the set operation difference.
now coming to the procedure..
Although there is inbuilt command in unix for doing this, but i has the limitation that..
1.)input files must be sorted.
2.)it gives the lines common to both not words..(not sure..u can check it)
the command is comm file1 file1
it's output is 3 column output..
1st column gives the file1-file2
2nd column gives the file2-file1
3rd column gives the common of file1 and file2
you can get only what u want by suppressing the option such as
using comm -12 file1 file2
it gives the lines common to both files.
CAUTION: It Requires the input file must contain the lines in sorted order.otherwise it will give unpredictable output.
now my answer is..
using cat and grep command...
grep -o "`cat file2`" file1
or
cat file1 | grep -o "`cat file2`"
2nd one is better in case of searching lines.
as it gives output as line wise.first one gives all matching lines in a single line.
string within quote makes content of file2 as searching pattern for file1.
-o option is set for printing only the matching word as output.
if u want the common lines in the two files use -x option of grep.
for finding the difference use -v option .
for finding the words ignoring the case use -i option of grep.
now, If u don't want to use cat in creating pattern.u can directly use -f option of grep command to provide pattern from a file.
grep -of file1 file2
is same as above command .all other option follows with it.
NOTE : one thing u should keep in mind while using -f option is that it must be last option. as above..
e.g. grep -fo file1 file2 will not work for the same.
It overcomes all the limitations of the comm command in unix.
i.e.
1.)It don't require input files in sorted order.
2.)matching words can be found not only lines.
I hope u will like it..
Feel free to comment ..if u feel any difficulty in understanding..
Thanks..
Enjoy Scripting............
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment