2011-03-18 29 views
2

,如果我有文件SOME_FILE命名,與內容如下:猛砸,sed的:具有多文件內容替換模式

first line 
second line 
third line 

和內部腳本:

VAR1="first line\nsecond line\nthird line" 
VAR2="`cat some_file`" 

我希望VAR1和VAR2是相同,但它顯然不是這樣根據sed:

sed "s/^a/${VAR1}/" some_another_file # this is OK 
sed "s/^a/${VAR2}/" some_another_file # this fail with syntactic error 

我想,換行表示我有點不同,但我找不到如何讓VAR2等於VAR1。

在此先感謝

+0

@ user665920:在編輯器中,然後按CTRL + K – Erik 2011-03-18 11:34:31

+0

請提交UNIX和GNU/Linux的選擇代碼/命令[unix.stackexchange.com](http://unix.stackexchange.com/)上相關的問題 – ierax 2011-03-18 11:37:42

回答

2

更改VAR1到:

VAR1=$(echo -e "first line\nsecond line\nthird line") 

然後對其進行測試:

$ [ "$VAR1" == "$VAR2" ] && echo equal 
equal 

更新:

爲了讓SED的工作,改變VAR2使其有「\ n」而不是換行符。

VAR2=$(sed ':a;N;$!ba;s/\n/\\n/g' some_file) 
sed "s/^a/${VAR2}/" file 
+0

好的,但我需要它的另一種方式。原始格式中的VAR1對於sed來說很好,但帶有換行符的VAR2會導致語法錯誤。 – 2011-03-18 13:27:41

+0

然後將VAR2更改爲:'VAR2 = $(sed':a; N; $!ba; s/\ n/\\ n/g'some_file)' – dogbane 2011-03-18 13:34:30

+0

就是這樣!謝謝 – 2011-03-18 14:46:16

4

這將在文件中讀取,並與它的內容替換行:

sed -e '/^a/{r some_file' -e 'd}' some_another_file