乍一看,似乎沒有成爲確定哪些匹配和如何處理替換的方法,所以在sed
一個調用你不妨使用三個不同的-e 's/…/…/'
參數對:
newpy=data
find='print(\"hc-takescreenshot: '\'
replace='doscreenshot(' # Dropped "
sed -e "s/$find.*1'\")/$replace\"This is the homepage\", \"1\", self)/" \
-e "s/$find.*2'\")/$replace\"This is another homepage\", \"2\", self)/" \
-e "s/$find.*3'\")/$replace\"This is yet another homepage\", \"3\", self)/" \
"$newpy"
該問題中使用的\x27
在Mac上不起作用(帶Bash 3);我用\'
來代替find
的末尾添加單引號。
然而,更嚴格的審查表明,(以及函數調用的變化),你可能想this
轉換爲This
和description'
到homepage"
原單引號數量爲雙引號號,接着是, self
。如果這是正確的,那麼你可以做到這一點與:
find='print(\"hc-takescreenshot: '\'
replace='doscreenshot("' # Reinstated "
sed -e "/$find/ {" \
-e "s//$replace/" \
-e "s/this/This/" \
-e "s/description'/homepage\"/" \
-e "s/'\([0-9]\)'\"/ \"\1\", self/" \
-e "}" \
"$newpy"
大括號組,以便只有線之間匹配$find
的命令由4個替換命令操作上。這簡化了匹配。 s//$replace/
使用sed
的「重用最後正則表達式」功能來避免重複腳本中的匹配字符串。
是的,如果你真的很喜歡無法讀取的代碼,並且不需要多次執行此操作,那麼你可以將所有腳本全部寫入一個-e
參數中。但是,只要您發現需要進行多次運行,最好將其拆分以便可讀。另一種選擇是創建一個包含普通sed
命令的文件(例如:script.sed
)(不必擔心外殼的處理引號):
/print("hc-takescreenshot: '/ {
s//doscreenshot("/
s/this/This/
s/description'/homepage"/
s/'\([0-9]\)'"/ "\1", self/
}
,然後你可以運行:
sed -i.bak -f script.sed "$newpy"
對於3個系的問題所示的輸入,所有的三個腳本生成的答案:
doscreenshot("This is the homepage", "1", self)
doscreenshot("This is another homepage", "2", self)
doscreenshot("This is yet another homepage", "3", self)
所有代碼現在在macOS Sierra 10.12.2上使用BSD sed
和GNU sed
和Bash 3.2.57(1)進行測試。
請看看:當有人回答我該怎麼辦我的問題?](http://stackoverflow.com/help/someone-answers) – Cyrus