I set the env variable like this
setenv ENV {"a":{"b":"http://c","d":"http://e"}}
I use sed like this
sed 's|(ENV)|('"$ENV"')|' aFile
It replaces (ENV)
with the following
(a:b:http://c a:d:http://e)
However if I set the variable like this within single quotes
setenv ENV '{"a":{"b":"http://c","d":"http://e"}}'
It replaces like this
({"a":{"b":"http://c","d":"http://e"}})
But I would like the output of sed for (ENV)
to be
('{"a":{"b":"http://c","d":"http://e"}}')
First of all, it's important to quote (or escape) your variable on definition (with setenv
), as explained in this answer, since braces and double quotes (among others) are metacharacters in C shell.
You can quote the complete value with single quotes:
$ setenv ABC '{"a":{"b":"http://c","d":"http://e"}}'
$ echo "$ABC"
{"a":{"b":"http://c","d":"http://e"}}
Or, escape metacharacters with backslashes, like this:
$ setenv ABC \{\"a\":\{\"b\":\"http://c\",\"d\":\"http://e\"\}\}
$ echo "$ABC"
{"a":{"b":"http://c","d":"http://e"}}
Now, for the sed
part of your question -- and how to quote the variable on replacement.
Just add single quotes in your sed
replacement expression and you're done:
$ setenv ABC '{"a":{"b":"http://c","d":"http://e"}}'
$ echo '(ABC)' | sed 's|(ABC)|('"'$ABC'"')|'
('{"a":{"b":"http://c","d":"http://e"}}')
Note, in addition, you should also take care of escaping sed
replacement metacharacters (these three only: \
, /
, and &
) in your variable. You seem aware of this, since you already use |
as a delimiter in you regex, but if you are unsure of what your variable contains, it's always good to escape it. For details on reliable escaping metacharacters in sed
, see this answer. In short, to escape a single-line replacement pattern, run it through sed 's/[&/\]/\\&/g'
.