Escaping the exclamation point in grep?

bash, grep, linux

Solution

You have a few options.

Use single quotes - when you need a literal single quote, just drop out of single quotes, add one with a backslash, and then go back in:

`grep 'rpm -qVa | awk '\''$2!="c" {print $0}'\' filename`

Use a POSIX string:

`grep $'rpm -qVA | awk \'$2!="c" {print $0}\'' filename`

Use a less-specific pattern:

`grep 'rpm -qvA | awk .$2.="c" {print $0}.' filename`

or, if you have checks for `$2=="c"` as well as `$2!="c"`, you could do something like this:

`grep 'rpm -qvA | awk .$2[^=]="c" {print $0}.' filename`

I would go with the POSIX string, or maybe the plain single-quote option - which has the debatable advantage of working in other shells, like `dash`.

Problem

I have this full line (the rpm command into awk below) that I want to grep out from certain files, including the quotes. I can't seem to be able to get the right output when I try grep, and grep -F. I tried deleting part of the tail end of line from the grep statement and it seems like the "!" causing the problems. I tried wrapping the string in single quotes and there is no luck as well. Thank you. ``` rpm -qVa | awk '$2!="c" {print $0}' ```

Original source