bash 逃避grep中的感叹号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13461828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:49:18  来源:igfitidea点击:

Escaping the exclamation point in grep?

linuxbashgrep

提问by tim tran

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.

我有这整行(下面 awk 中的 rpm 命令),我想从某些文件(包括引号)中提取出来。当我尝试 grep 和 grep -F 时,我似乎无法获得正确的输出。我尝试从 grep 语句中删除行尾的一部分,它看起来像“!” 造成问题。我尝试将字符串用单引号括起来,但也没有运气。谢谢你。

rpm -qVa | awk '!="c" {print 
rpm -qVa | awk '$2!="c" {print ##代码##}'
}'

回答by Mark Reed

You have a few options.

你有几个选择。

  1. 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

  2. Use a POSIX string:

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

  3. 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

  1. 使用单引号——当你需要一个文字单引号时,只需去掉单引号,用反斜杠添加一个,然后返回:

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

  2. 使用 POSIX 字符串:

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

  3. 使用不太具体的模式:

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

    或者,如果您有$2=="c"以及 的检查$2!="c",您可以执行以下操作:

    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.

我会使用 POSIX 字符串,或者可能是普通的单引号选项 - 它具有在其他 shell 中工作的有争议的优势,例如dash.

回答by CuriousMind

A backslash should do the trick

反斜杠应该可以解决问题

##代码##