A K
A K

Reputation: 747

sed won't perform the required subs inside shell script

In the below shell script I try to print A2D(Vlog-Ams-@Cross) with special characters escaped. For example replace ( with \( but sed won't have any effect.

#! /bin/sh
parameter="A2D(Vlog-Ams-@Cross)"
echo $parameter
parameterz=`echo "$parameter" | sed 's/(/\\(/g'`
echo $parameterz

The output is

A2D(Vlog-Ams-@Cross)
A2D(Vlog-Ams-@Cross)

If I do the same on my c-shell terminal, it works fine.

Any ideas?

Upvotes: 1

Views: 111

Answers (2)

Uwe
Uwe

Reputation: 728

You use backslashs within a backtick command and that's tricky. If the sed command didn't occur within backticks, it would work correctly. When the shell looks for the closing backtick, however, it removes one level of backslash quoting, so you get

sed 's/(/\(/g'

and that's a no-op. If your shell permits it, use $(...) instead of backticks; in this way you avoid these quoting problems.

Upvotes: 2

user647772
user647772

Reputation:

In your replacement \\( the first \ escapes the second \. But you must escape the (, too:

$  echo 'A2D(Vlog-Ams-@Cross)' | sed -e 's/(/\\\(/g' -e 's/)/\\\)/g'
A2D\(Vlog-Ams-@Cross\)

Upvotes: 1

Related Questions