Lou Diamonds
Lou Diamonds

Reputation: 51

Grep exact match string with spaces as variable

I have:

file.csv

Which contains

2,1,"string with spaces",3,4,5
2,1,"some other string",3,4,5
2,1,"string with spaces more than this",3,4,5
2,1,"yet another",3,4,5
2,1,"string with spaces too",3,4,5

When I do this:

grep '"string with spaces",' file.csv

It produces the desired out come which is:

2,1,"string with spaces",3,4,5

Now I need to do this in a while loop:

while read p; do

    grep '"$p",' file.csv

done < list.txt

Where:

list.txt

contains:

string with spaces
yet another

And my desired output is:

2,1,"string with spaces",3,4,5
2,1,"yet another",3,4,5

The problem is that my while loop comes back empty, or matches partially. How do I loop through list.txt & get my desired output?

Upvotes: 1

Views: 1360

Answers (3)

kvantour
kvantour

Reputation: 26481

 grep -Ff strings.txt file.csv

This should get you far enough.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133508

If you are ok with awk this should be an easy one for it.

awk 'FNR==NR{a[$0];next} ($4 in a)' list.txt FS="[,\"]" file.csv

OR(as per Ed sir's comment to make field separator as comma and keep it clearer, one could try following)

awk -F, 'FNR==NR{a["\""$0"\""];next} $3 in a' list.txt file.csv

Output will be as follows.

2,1,"string with spaces",3,4,5
2,1,"yet another",3,4,5

Upvotes: 4

Marcus
Marcus

Reputation: 3524

Your string quoting is all using single quotes ' which does not do any interpolation of the $p variable. Changing it to grep '"'"$p"'",' file.csv will solve the problem. The key is that here the variable interpolation is done inside of double quotes " and then concatenated with the strings containing actual double quote " characters.

A more (or less, depending on your point of view) readable version could look like this: grep "\"$p\"," file.csv

Upvotes: 2

Related Questions