How to match a single quote in sed

2019-01-14 01:26发布

问题:

How to match a single quote in sed if the expression is enclosed in single quotes:

sed -e '...'

For example need to match this text:

'foo'

回答1:

You can either use:

"texta'textb" (APOSTROPHE inside QUOTATION MARKs)

or

'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)

I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.

In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.



回答2:

As noted in the comments to the question, it's not really about sed, but how to include a quote in a quoted string in a shell (e.g. bash).

To clarify a previous answer, you need to escape the quote with a backslash, but you can't do that within a single-quoted expression. From the bash man page:

Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

Therefore, you need to terminate the quoted expression, insert the escaped quote, and start a new quoted expression. The shell's quote removal does not add any extra spaces, so in effect you get string concatenation.

So, to answer the original question of how to single quote the expression 'foo', you would do something like this:

sed -e '...'\''foo'\''...'

(where '...' is the rest of the sed expression).

Overall, for the sake of readability, you'd be much better off changing the surrounding quotes to double quotes if at all possible:

sed -e "...'foo'..."

[As an example of the potential maintenance nightmare of the first (single quote) approach, note how StackOverflow's syntax highlighting colours the quotes, backslashes and other text -- it's definitely not correct.]