Grep exact match in double quotes
Hi guys , i am struggling with this code for hours and i can not get a perfect solution for it .
Grep with -w switch catches the exact match but i need grep to search a pattern in double quotes . example : text Quote:
like : var1='"my text"' 1st - i can not get pass parsing the double quotes to grep -w like grep '$var1' myfile 2nd - escaping the grep with Code:
grep -w '\$var1\" myfile Because when i search without those quotes example : my text then grep will pop up lines 1 ,3 and 4 from the quoted text before . Is there a way to do this ? tell grep -w to include the double quotes inside the search ? |
You'll need to escape any double quotes you include inside the regular double quotes:
Code:
var="my text" Code:
var="\"my text\"" |
Next time read the part i wrote :
"consider these grep searches will be under a variable" i wrote that because in fact it is a variable and the text in var does not come escaped . |
Right. And I gave you two methods to solve that, though spelled the variables wrong. It solves the task you described above.
If the above answer did not solve your task then you'll have to reword it and include the missing material. |
Another example more quickly understandable
textfile : myfile.txt Quote:
Code:
#!/bin/bash |
yup , sorry i post after you without notice it .
yes , if the var already comes with quotes then i dont need to write the -w switch . I will test it here on my code . Thanks |
No problem. However, based on the update, I would say this way and have the sed script escape the quotes:
Code:
var1=$(sed -n '3p; s|"|\\"|g' myfile) |
Quote:
There are two possible cases I see: 1. The double quotes you want to find are not included in the variable value but you want to grep for that value only when surrounded by double quotes, which is handled by Turbocapitalist's first suggestion: Quote:
Quote:
|
Thank you Turbocapitalist , it works like a charm
The code that i tested and worked great was : Quote:
However , adapting my little script with your code would be like this : Code:
#!/bin/bash |
Quote:
Code:
#!/bin/bash I'm not saying that what you're doing is wrong. Just pointing out that it may be unnecessary, unless you have a need for the value in a variable other than to display it. |
All times are GMT -5. The time now is 03:03 AM. |