I'm trying to use sed, but my pattern contains [] brackets and slashes (/).

I've tried quotes, but it doesn't help.

How do I escape it?


$ sed -i'.bak' "s/^includes[] =/;includes[] =/g" *.make
sed: 1: "s/^includes[] =/;includ ...": unterminated substitute in regular expression
$ sed -i'.bak' 's/^includes[] = includes/;includes/g' *.make
sed: 1: "s@^includes[] = i ...": unbalanced brackets ([])
$ sed -i'.bak' 's/^includes[] = foo/includes//;includes[] = foo/includes//g' *.make
sed: 1: "s/^includes[] = foo/inc ...": bad flag in substitute command: '/'
  • 1
    For your particular example, it seems you want to add a semicolon to the beginning of every line starting with includes. You can just do sed 's/^includes/;&/' your_file where & is what was matched by the regex. – Joseph R. Nov 5 '14 at 1:40

To escape slashes, you can use any character other than a forward slash to separate regular expressions.

E.g. (foo1/ -> foo2/):

sed "s@foo1/@foo2/@"
sed "s|foo1/|foo2/|"

To escape brackets (this work also for slashes) you've to put a backslash character before the delimiting character causes the character to be treated literally.

E.g. (foo[] = -> ;foo[] =):

sed "s/foo\[\] =/;foo\[\] =/"

Read more by running man sed (Sed Regular Expressions).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.