Craig Dabelstein
Craig Dabelstein

Reputation: 43

How to escape characters in sed

I'm trying to remove some text from multiple files using sed. This is the text I'm trying to delete:

\once override TupletBracket #'stencil = ##f

I've tried this line in sed but I can't get it to work:

sed -i '' -e 's/\\once \\override TupletBracket #'stencil = ##f//g' *ily

I've tried escaping the # symbols, the ' and the = but still no joy. Could anyone please point me in the right direction?

Upvotes: 2

Views: 7925

Answers (3)

dan4thewin
dan4thewin

Reputation: 1184

I think it's better to use single quotes here rather than double quotes to avoid the extra \s and other possible expansions (e.g. variables). Where you want a literal single quote, you close the quotation, add \', and then start a new quotation for the remainder.

$ cat in
before \once override TupletBracket #'stencil = ##f after
$ sed 's/\\once override TupletBracket #'\''stencil = ##f//g' in
before  after

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203985

# and = are not RE metacharacters nor do they have any other special meaning to sed within a regexp (= does outside of a regexp) unless the regexp is delimited with one of them so there's no reason to escape them in your script. ' only has significance if the whole script is delimited with 's since in shell no script that's delimited by a given character can include that character. So here's your choices:

$ echo "seab'cd" | sed 's/b'\''c/foo/'
seafood

$ echo "seab'cd" | sed "s/b'c/foo/"
seafood

Note that if you use the second (double quotes) version then you're allowing shell variables to expand inside the script and would require double-backslashes to escape chars.

I expected using the octal representation of a ' (i.e. \047) would work too like it does in awk:

$ echo "seab'cd" | awk '{sub(/b\047c/,"foo")}1'
seafood

but it didn't:

$ echo "seab'cd" | sed 's/b\047c/foo/'
seab'cd

and I suspect that's because sed is treating \0 as a backreference. It does work with the hex representation:

$ echo "seab'cd" | sed 's/b\x27c/foo/'
seafood

but that's dangerous and should be avoided (see http://awk.freeshell.org/PrintASingleQuote).

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

you can't use ' directly inside sed command that is quoted using '. Use a double quotes instead and to match \ you'll need to use \\\ to have \\ i.e \.

$ sed "s/\\\once override TupletBracket #'stencil = ##f//g"
\once override TupletBracket #'stencil = ##f

hello \once override TupletBracket #'stencil = ##f xyz
hello  xyz
$

Upvotes: 0

Related Questions