2014-09-19 142 views
0

輸入文件我有看起來像這樣搜索字符串

Topic1 
Some text 
Topic2 
Some text 
Topic3 
Some text 

我需要去TOPIC2然後更換「一些文本」與「實際投入」

以下腳本作品

/Topic2/,/Topic/ { 
/Some text/c 
Actual input 
} 

有沒有更簡單的方法來做到這一點。我希望以下將起作用,但事實並非如此。

/Topic2/ { 
/Some text/c 
Actual input 
} 

更新:應該已經說得更清楚了。我只是在尋找基於sed的解決方案。

回答

1

這可能爲你工作(GNU SED):

sed -e '/Topic2/,/Topic/{//!d;/Topic2/a\bla\nbla\nbla' -e '}' file 

或:

sed -e '/Topic2/,/Topic/{//!d;/Topic2/r fileb' -e '}' filea 

,或者使用Bash:

sed $'/Topic2/,/Topic/{//!d;/Topic2/a\\bla\\nbla\\nbla\n}' file 

編輯:

sed $'/Topic2/{:a;n;/Some text/!ba;c\\Actual input\n}' file 
+0

看起來像 「範圍」(/ start_range /,/ end_range /)是這樣做的唯一途徑。我給出的第二個例子不起作用。 – user1074593 2014-09-22 21:46:14

+0

@ user1074593請參閱編輯 – potong 2014-09-23 12:28:56

1

用awk怎麼樣?

awk 'p&&/Topic/{p=0}/Topic2/{p=1}p{gsub(/Some text/,"foo\nbar\nbla\nline")}7' file 

以上我使用多行替換爲例如,與輸入輸出將是:

Topic1 
Some text 
Topic2 
foo 
bar 
bla 
line 
Topic3 

可以傳遞替換字符串來awk的作爲殼變量,使得AWK單班輪將是靈活的。像:

kent$ r="a 
b 
c" 

kent$ awk -v rep="$r" 'p&&/Topic/{p=0}/Topic2/{p=1}p{gsub(/Some text/,rep)}7' f 
Topic1 
Some text 
Topic2 
a 
b 
c 
Topic3 
Some text 
0

這裏是一個gnu awk解決方案:

awk -v RS="Topic[0-9]*" 'f=="Topic2" {$0="\nActual input\n"} NR>1{print f,$0} {f=RT}' file 
Topic1 
Some text 

Topic2 
Actual input 

Topic3 
Some text