简体   繁体   English

如何在Bash / Grep中删除单引号?

[英]How to escape single quotes in Bash/Grep?

I want to search with grep for a string that looks like this: 我想用grep搜索一个如下所示的字符串:

something ~* 'bla'

I tried this, but the shell removes the single quotes argh.. 我试过这个,但是shell删除了单引号argh ..

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

What would be the correct search? 什么是正确的搜索?

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 ~]$ 

:-) :-)

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 ~\\*匹配表达式~*后的something
  • use double brackets around :alnum: (see example here ) 使用双括号:alnum:这里的例子)
  • use a * after [[:alnum::]] to match not only one character between your single quotes but several of them [[:alnum::]]之后使用*不仅可以匹配单引号中的一个字符,还可以匹配其中的几个字符
  • the single quotes don't have to be escaped at all because they are contained in an expression that is limited by double quotes. 单引号根本不必转义,因为它们包含在受双引号限制的表达式中。
  • character classes are specified with [[:alnum:]] (two brackets) 字符类用[[:alnum:]] (两个括号)
  • [[:alnum:]] is matching only one character. [[:alnum:]]只匹配一个字符。 To match zero or more characters [[:alnum:]]* 匹配零个或多个字符[[:alnum:]]*
  • you can just use " " to quote the regex: 你可以用" "来引用正则表达式:

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

Matteo 马特奥

It seems as per your expression, that you are using first ' , then " . If you want to escape the single quotes, you can either use ' and escape them, or use double quotes. Also, as Matteo comments, character classes have double square brackets Either: 根据你的表达式,你首先使用' ,然后" 。如果你想要转义单引号,你可以使用'并转义它们,或使用双引号。另外,作为Matteo注释,字符类有双方括号要么:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM