2016-12-17 28 views
0

我試圖改變線路這樣在更換兩個字符串的Sed則

print("hc-takescreenshot: 'this is the description','1'") 
print("hc-takescreenshot: 'this is another description','2'") 
print("hc-takescreenshot: 'this is yet another description','3'") 

這個

doscreenshot("This is the homepage", "1", self) 
doscreenshot("This is another homepage", "2", self) 
doscreenshot("This is yet another homepage", "3", self) 

我可以做這樣的事情

find='print(\"hc-takescreenshot: \x27' 
replace='doscreenshot("' 
sed -i -e "s/$find/$replace/g" $newpy 

但是,只有涉及第一部分,然後我需要替換最後一位,例如:'3'「)

我需要做的是在比賽進行時延長替換時間。

+0

請看看:當有人回答我該怎麼辦我的問題?](http://stackoverflow.com/help/someone-answers) – Cyrus

回答

1

假設你想保持This is...描述字符串(目前尚不清楚閱讀您的問題),你可以試試這個:

sed -i -e "s/.*: '\([^']*\)','\([0-9]*\)'.*/doscreenshot(\"\1\", \"\2\", self)/" "$newpy" 
+0

有一個缺少雙引號,所以實際上是這樣的:sed -i -e「s /.*:'\([^' ] * \')','\([0-9] * \)'。*/doscreenshot(\「\ 1 \」,\「\ 2 \」,self)/「」$ newpy「 - 除此之外完美地做了我想要的,謝謝 – mozman2

+0

不客氣@ mozman2。我編輯添加缺少的'''。 – SLePort

0

乍一看,似乎沒有成爲確定哪些匹配和如何處理替換的方法,所以在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轉換爲Thisdescription'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)進行測試。