Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape single quotes in Bash/Grep?

I want to search with grep for a string that looks like this:

something ~* 'bla' 

I tried this, but the shell removes the single quotes argh..

grep -i '"something ~* '[:alnum:]'"' /var/log/syslog 

What would be the correct search?

like image 994
JohnnyFromBF Avatar asked Aug 31 '11 08:08

JohnnyFromBF


People also ask

How do I escape a quote from a bash string?

Bash escape character is defined by non-quoted backslash (\). It preserves the literal value of the character followed by this symbol. Normally, $ symbol is used in bash to represent any defined variable.

How do you escape characters in grep?

Searching for Metacharacters. To use the grep command to search for metacharacters such as & ! . * ? and \ , precede the metacharacter with a backslash (\). The backslash tells grep to ignore (escape) the metacharacter.

How do I escape a single quote in Linux?

A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word.

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.


1 Answers

If you do need to look for quotes in quotes in quotes, there are ugly constructs that will do it.

echo 'And I said, "he said WHAT?"' 

works as expected, but for another level of nesting, the following doesn't work as expected:

echo 'She said, "And I said, \'he said WHAT?\'"' 

Instead, you need to escape the inner single quotes outside the single-quoted string:

echo 'She said, "And I said, '\''he said WHAT?'\''"' 

Or, if you prefer:

echo 'She said, "And I said, '"'"'he said WHAT?'"'"'"' 

It ain't pretty, but it works. :)

Of course, all this is moot if you put things in variables.

[ghoti@pc ~]$ i_said="he said WHAT?" [ghoti@pc ~]$ she_said="And I said, '$i_said'" [ghoti@pc ~]$ printf 'She said: "%s"\n' "$she_said" She said: "And I said, 'he said WHAT?'" [ghoti@pc ~]$  

:-)

like image 137
ghoti Avatar answered Sep 20 '22 17:09

ghoti