user3074653
user3074653

Reputation: 49

Unix/Linux Bash Scripting: sed doesn't respect spaces

I'm trying to develop a bash script which will be replacing/appending some lines in configuration files. I'm having an issue where sed isn't respecting spaces in my replaced line. This is what I've setup:

sedkey="org.apache.catalina.core.ThreadLocalLeakPreventionListener"
sednew="<Listener\ className=\"org.apache.catalina.mbeans.JmxRemoteLifecycleListener\"\ rmiRegistryPortPlatform=\"7050\"\ rmiServerPortPlatform=\"7051\"\ \/\>"

sed -e "/"$sedkey"/a\\
"$sednew"" server-wc.xml

But when I run the script containing this, I get this:

sed: can't read className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"\: No such file or directory
sed: can't read rmiRegistryPortPlatform="7050"\: No such file or directory
sed: can't read rmiServerPortPlatform="7051"\: No such file or directory
sed: can't read \/\>: No such file or directory

While it adds the less than sign and "Listener" perfectly fine.

So my question is, what am I doing wrong?

Upvotes: 0

Views: 298

Answers (2)

that other guy
that other guy

Reputation: 123470

Always quoting variables and command expansions is good practice, but blindly putting quotes left and right of them is not.

In this case, the quotes around the expansion are unquoting it, because the left quote is terminating an existing double quoted string, while the right quote starts a new one. Example:

echo "You enter "$HOSTNAME". You can smell the wumpus."
     |----------|         |---------------------------|
        Quoted   No quotes           Quoted

In other words, you should just be using:

sed -e "/$sedkey/a\\
$sednew" server-wc.xml

ShellCheck automatically points this out. This info was copied from its wiki. Also consider using an XML tool like xmlstarlet instead of sed.

Upvotes: 1

user3074653
user3074653

Reputation: 49

Using single quotes instead of double quotes in the sed command to remove conflict with double quotes in variable, so that the sed command looks like:

sed '/'"$sedkey"'/a\'"$sednew" server-wc.xml

Thank you Sundeep!

Upvotes: 0

Related Questions