关于sed问题中引号的使用

  • 本文关键字:sed 问题 关于 bash
  • 更新时间 :
  • 英文 :


好吧。谢谢你的好心帮助。我从你那里学到了,要在sed中使用变量,我们必须使用"而不是"。然而,在我的情况下,在我使用"和不带变量之前,它工作得很好。在使用"和变量($title,$web,$desc(后,它不再起作用,原因是什么??谢谢

之前

sed -i '0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">n <title>test1</title>n <guid>test2</guid>n <link>test3</link>n <description><![CDATA[<p>test4</p>]]></description>n </item>n<item pop="N">/ }' /var/www/html/INFOSEC/english/rss/test.xml

之后

sed -i "0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">n <title>News: $title</title>n <guid>$web</guid>n <link>$web</link>n <description><![CDATA[<p>$desc</p>]]></description>n </item>n<item pop="N">/ }" /var/www/html/INFOSEC/english/rss/test.xml

我单独运行了它,而不是整个脚本结果是错误的bash:![CDATA[:找不到事件,实际上我不应该单独运行它,因为我需要在变量中输入一些东西

您在字符串中使用"。这些字符需要转义。

此外,您的shell很可能在""中转义字符,而不是在''中转义。您至少有两种解决方案:

要么保留""中的所有内容,但用\替换,用":替换"

 sed -i "0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">\n <title>News: $title<...

或者将两者混合;当需要插入变量时,退出',在""中输入变量,然后重新输入':

 sed -i '0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">n <title>News: '"$title"'<...

切换它们。只要引用的部分是连续的,bash就会将它们视为一个字符串。

sed -i '0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">n <title>News: '"$title"'</title>n <guid>'"$web"'</guid>n <link>'"$web"'</link>n <description><![CDATA[<p>'"$desc"'</p>]]></description>n </item>n<item pop="N">/ }' /var/www/html/INFOSEC/english/rss/test.xml

当shell在双引号内看到!时,将触发Bash历史扩展。这就是出现"找不到事件"错误消息的原因。来自手册:

只能使用"\"one_answers"来转义历史扩展字符。

你可以这样做:

sed_script='0,/<item pop="N">/ { s/<item pop="N">/<item pop="N">n <title>News: %s</title>n <guid>%s</guid>n <link>%s</link>n <description><![CDATA[<p>%s</p>]]></description>n </item>n<item pop="N">/ }'
sed -i "$(printf "$sed_script" "$title" "$web" "$web" "$desc")" /var/www/html/INFOSEC/english/rss/test.xml

或者(我不是sed专家(,这同样有效吗?可读性更强

sed_script='/<item pop="N">/ a 
<title>News: %s</title> 
<guid>%s</guid>n <link>%s</link> 
<description><![CDATA[<p>%s</p>]]></description> 
</item> 
<item pop="N">'
sed -i "$(printf "$sed_script" "$title" "$web" "$web" "$desc")" /var/www/html/INFOSEC/english/rss/test.xml

最新更新