Search code examples
linuxbashescapinggrep

How can I 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?


Solution

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

    works for me.

    • escape the first * to match a literal * instead of making it the zero-or-more-matches character:
      ~* would match zero or more occurrences of ~ while
      ~\* matches the expression ~* after something
    • use double brackets around :alnum: (see example here)
    • use a * after [[:alnum::]] to match not only one character between your single quotes but several of them
    • the single quotes don't have to be escaped at all because they are contained in an expression that is limited by double quotes.