franky
franky

Reputation: 53

sed got error if no single quotes around the regular expression

I tried to do the following command in bash:

ls -1 | sed s/\(.*\)/"\1"/

which is add double quotes around each output of ls, but the result shows sed: 1: "s/(.*)/\1/": \1 not defined in the RE

after I add single quotes around the regular expression, I got the right result. the right one is:

ls -1 | sed 's/\(.*\)/"\1"/'

theocratically I do not need the outer quotes right? any one has the same experience?

Upvotes: 0

Views: 1284

Answers (2)

glenn jackman
glenn jackman

Reputation: 247042

Sending the command to echo will show you what sed sees

$ echo sed s/\(.*\)/"\1"/
sed

Hmm, the sed script disappeared altogether. The exposed "*" is forcing the shell to try to match files. Let's disable that:

$ set -f
$ echo sed s/\(.*\)/"\1"/
sed s/(.*)/\1/

The shell ate the quotes and the backslashes. Quoting the sed script:

$ echo sed 's/\(.*\)/"\1"/'
sed s/\(.*\)/"\1"/

That gives the right result, sed will see the script you want to give it. How can we do that without quotes

$ echo sed s/\\\(.\*\\\)/\"\\1\"/
sed s/\(.*\)/"\1"/

And that's ugly.

Upvotes: 2

wRAR
wRAR

Reputation: 25559

Single quotes are used to disable shell parsing of various sequences including backslash escapes. If you don't use them, your sequences like \( are passed to sed as (. You may check that by adding echo to the beginning of your command.

Upvotes: 3

Related Questions