2011-07-19 10 views
1

好吧。感謝您的所有幫助。我從你那裏學習,要在sed中使用一個變量,我們必須使用「」而不是「'。但是,就我而言,在我使用''且沒有變量之前,它運行良好。在使用「」和變量($ title,$ web,$ desc)之後,它不再起作用,原因是什麼?謝謝。關於在sed問題中使用引號

之前

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 [:事件沒有發現,其實我不應該單獨運行,因爲我需要在變量中輸入內容

回答

2

您在字符串中使用"。這些字符需要被轉義。

此外,您的shell可能會轉義""中的\字符,而不是在''之內。您至少有兩種解決方案:

要麼保持裏面的一切""\\取代\,並" s的\"

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

或者兩者混合使用;當你需要插入一個變量,出口',進入裏面""您的變量,並重新進入':當shell看到!雙引號內

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

將它們切換起來。只要引用的部分是連續的,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 
+0

我沒有意識到techique之前,謝謝 –

0

猛砸history expansion將觸發。這就是出現「未找到事件」錯誤消息的原因。從手冊:

只有'\'和'''可用於轉義歷史擴展字符。

你可以這樣做:

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