Reputation: 1
I m new to bash Shell scripting. I have a requirement that I have a lookup file (csv) in which there are set of strings in it like below.
file1:
text1
text2
text3
I have to check whether the strings in file1 are present in the file2.
file2:
s.no desc
1 text5
2 text3
3 text2
4 text9
If the the string in file1 is there in file2, then I have to print the output in a new file file3 with the s.no and the string found. Please help.
Upvotes: 0
Views: 418
Reputation: 8093
Use
grep --file=file1 file2
or
grep -f file1 file2
From manual page of grep
-f FILE, --file=FILE Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)
Note: Add -w
if you want only exact word match. So footext3bar
will not be matched with text3
.
Also of file1
contains regular expressing keywords like *
or ^
then add -F
also.
So updated command would be
grep -Fwf file1 file2
Example
bash-4.2$ cat file1
text1
text2
text3
bash-4.2$ cat file2
s.no desc
1 text5
2 text3
3 text2
4 text9
bash-4.2$
bash-4.2$ grep --file=file1 file2
2 text3
3 text2
Upvotes: 1