Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

linux - How to 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
' "$she_said"
She said: "And I said, 'he said WHAT?'"
[ghoti@pc ~]$ 

:-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...