我正在尝试开发一个bash脚本,它将替换/追加配置文件中的一些行。我有一个问题,sed不尊重我的替换行中的空间。这就是我设置的:

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

但是当我运行包含这个的脚本时,我得到了这个:
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

虽然它添加了小于号和“监听器”非常好。
所以我的问题是,我做错了什么?

最佳答案

总是引用变量和命令扩展是很好的实践,但盲目地在变量和命令扩展的左边和右边添加引号则不是。
在这种情况下,围绕扩展的引号不引用它,因为左引号终止了现有的双引号字符串,而右引号则开始一个新引号。例子:

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

换句话说,你应该使用:
sed -e "/$sedkey/a\\
$sednew" server-wc.xml

ShellCheck自动指出这一点。此信息是从its wiki复制的。还可以考虑使用类似xmlstarlet的XML工具,而不是sed

关于linux - Unix/Linux Bash脚本:sed不尊重空格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45062335/

10-16 20:48