Reputation: 13
I'm trying to grep strings from file2.csv using existing strings from file1.csv and write matched lines to result.csv file. A have a following bash script:
cat file1.csv | while read line; do
grep $line ./file2.csv > result.csv
done
But afterall the result.csv is always empty. When I do manual grep from file2.csv everything works fine. What I do wrong?
file1.csv:
15098662745072
15098662745508
file2.csv:
";"0";"15098662745072";"4590";"4590";"
";"0";"15098662745508";"6400";"6400";"
";"0";"15098662745515";"6110";"6110";"
";"0";"15098662745812";"7970";"7970";"
expected result (result.csv):
";"0";"15098662745072";"4590";"4590";"
";"0";"15098662745508";"6400";"6400";"
Upvotes: 1
Views: 378
Reputation: 203324
You should be using awk for this, not grep, because:
a) grep does not by default look for strings, it looks for regular expressions. You need to use fgrep
or grep -F
or awk
instead of grep
to search for strings.
b) You really only want to match the numbers from file1.csv when they appear as a full specific field in file2.csv, not wherever they occur on the line.
awk -F'";"' 'NR==FNR{a[$0];next} $3 in a' file1.csv file2.csv > result.csv
Upvotes: 1
Reputation: 274562
>
keeps overwriting the file. Use >>
to append to it.
Instead of using a loop, you can simply use the -f
option in grep
to make grep
read patterns from the file.
grep -f file1.csv file2.csv > result.csv
If you have to use a loop, use the following approach:
while read line; do
grep "$line" ./file2.csv
done < file1.csv > result.csv
Upvotes: 4