[英]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. 适合我。
*
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
:alnum:
(see example here ) :alnum:
见这里的例子) *
after [[:alnum::]]
to match not only one character between your single quotes but several of them [[:alnum::]]
之后使用*
不仅可以匹配单引号中的一个字符,还可以匹配其中的几个字符 [[: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.