I am looking for a string within quotation marks where the word Linux occurs somewhere between parentheses which reside somewhere inside the quotation marks. I have to use a regular expression to do that. I am required to do it in a Linux OS (using Virtual Box Terminal). I used the following regex:

 egrep "\"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?\"" [FILE]

But the problem is, I get

bash: syntax error near unexpected token '("

every time. What can be the problem? I tried this regex in "http://regexr.com/" it works fine, there is nothing wrong with the regex. But the Linux shell always produces the same problem... I used "\" in front of parentheses because they are metacharacters. The same thing I did in front of double quotes... But it does not work. Could anybody help me, please?


The problem is the unescaped double quotes inside the expression, for example around this part "]*)?\(([^]". If you want to pass literal ", including inside double quotes or () or [], then you have to quote the quotes! You could do

egrep "\"([^\"]*)?\(([^\"]*)?Linux([^\"]*)?\)([^\"]*)?\"" FILE

But a less ugly way is to quote the whole expression with single quotes, and in general always strong (single) quote your regex so the shell does not do anything weird to it before it's passed as an argument to egrep or whatever program you're using:

egrep '"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?"' FILE

(now you do not need to escape the double quotes on the outside either, but you need the other backslashes to make the parentheses literal (in ERE))

if you don't want the rest of the line, add -o (match only) also

egrep -o '"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?"' FILE

You didn't give an example so I made a silly one... here is is before:

where is "the (lost Linux that I want) to find somewhere" in this file
and some junk
we don't want this thing "here where Linux is (not in brackets)"

and after:

"the (lost Linux that I want) to find somewhere"

(NB: using GNU grep you can do grep -E instead of using egrep)

| improve this answer | |

Replace the first and the last double quote " with a single quote '.

egrep '\"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?\"' [FILE]
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.