2011-07-22 67 views
16

什麼是用於mac shell腳本的sed命令,它將用myFile.txt的整個字符串內容替換字符串「fox」的所有迭代。使用SED文件的內容替換字符串

myFile.txt是帶換行符和各種字符的html內容。一個例子是

</div> 
    </div> 
    <br> 
    <div id="container2"> 
    <div class="question" onclick="javascript:show('answer2')";> 

謝謝!

編輯1

這是我的實際代碼:

sed -i.bkp '/Q/{ 
s/Q//g 
r /Users/ericbrotto/Desktop/question.txt 
}' $file 

當我運行它,我得到:

sed in place editing only works for regular files. 

而且在我的檔案Q由一噸取代漢字(!)。離奇!

+0

見http://stackoverflow.com/questions/6684487/sed-replace-with-variable-with-multiple-lines/6685563#6685563。這將是一個解決方案。祝你好運。 – shellter

+0

關於編輯1 ...您的原始文件可以使用擴展名「.bkp」。你的'question.txt'文件的內容是什麼?另外,'$ file'引用的文件的內容是什麼。是否有一些二進制文件?他們的編碼是什麼? – brandizzi

+0

question.txt文件的內容正是上面所示的html。 $文件引用的文件是.txt文件。我的.bkp部分有問題嗎?我應該將其更改爲.txt嗎?我現在將檢查我的question.txt文件的編碼。 –

回答

40

您可以使用r命令。當你發現在輸入 '狐狸' ......

/fox/{ 

...更換白白...

s/fox//g 

...並讀取輸入文件:

r f.html 
} 

如果你有一個文件,如:

$ cat file.txt 
the 
quick 
brown 
fox 
jumps 
over 
the lazy dog 
fox dog 

結果是:

$ sed '/fox/{ 
    s/fox//g 
    r f.html 
}' file.txt 
the 
quick 
brown 

    </div> 
    </div> 
    <br> 
    <div id="container2"> 
    <div class="question" onclick="javascript:show('answer2')";> 
jumps 
over 
the lazy dog 
dog 
    </div> 
    </div> 
    <br> 
    <div id="container2"> 
    <div class="question" onclick="javascript:show('answer2')";> 

編輯:改變正在處理的文件,只要傳遞-i標誌的sed:

sed -i '/fox/{ 
    s/fox//g 
    r f.html 
}' file.txt 

一些SED版本(如我自己一個人)需要你傳遞一個拓-i標誌,這將是一個備份文件的擴展名與舊內容的文件:

sed -i.bkp '/fox/{ 
    s/fox//g 
    r f.html 
}' file.txt 

這裏是同樣的事情,作爲一個襯墊,這也與Makefile文件兼容

sed -i -e '/fox/{r f.html' -e 'd}' 
+0

這完全有效!給這個人榮譽勳章!最後一件事Brandizzi ...這是打印到控制檯,但不是文件。我們可以得到一些代碼來做到這一點嗎?太感謝了! –

+0

當然可以!我編輯了我的答案。 – brandizzi

+0

Brandizzi。得到一些奇怪的行爲。你能檢查我的編輯1嗎? –

2

最終我與去比很多解決方案我在網上找到的要簡單得多:

str=xxxx 
sed -e "/$str/r FileB" -e "/$str/d" FileA 

支持模板,像這樣:

str=xxxx 
sed -e "/$str/r $fileToInsert" -e "/$str/d" $fileToModify 
+0

這實際上有效。 –

+1

如果匹配的str不是全部在單行上,則這不起作用。即使部分字符串匹配,這將用fileToInsert的內容替換整行 – saGii