2012-04-03 56 views
1

我想用第一行#之間的任何內容替換字符串(在本例中爲Linux)。使用Sed替換從正則表達式獲得的另一個字符串的字符串

所以我想轉:

#Windows# 
1. Linux Sysadmin, Linux Scripting etc. 
2. Databases - Oracle, mySQL etc. 
3. Security (Firewall, Network, Online Security etc) 
4. Storage in Linux 
5. Productivity (Too many technologies to explore, not much time available) 

到:

1. Windows Sysadmin, Windows Scripting etc. 
2. Databases - Oracle, mySQL etc. 
3. Security (Firewall, Network, Online Security etc) 
4. Storage in Windows 
5. Productivity (Too many technologies to explore, not much time available) 

#Solaris# 
1. Linux Sysadmin, Linux Scripting etc. 
2. Databases - Oracle, mySQL etc. 
3. Security (Firewall, Network, Online Security etc) 
4. Storage in Linux 
5. Productivity (Too many technologies to explore, not much time available) 

到:

1. Solaris Sysadmin, Solaris Scripting etc. 
2. Databases - Oracle, mySQL etc. 
3. Security (Firewall, Network, Online Security etc) 
4. Storage in Solaris 
5. Productivity (Too many technologies to explore, not much time available) 

只需使用sed。 我得儘可能: sed的 ' /^#[A-ZA-Z] */{ ^ h d } /Linux的/ G'

我想我需要做的是運行正則表達式使用保持緩衝區作爲替代模式,我想看起來像s/Linux/g但我找不到一種方法來做到這一點。 任何人有任何想法?

回答

2

這裏是一個sed的解決方案:

sed ' 
/^#.*#$/{      # if replacement text is matchd 
s/#//g       # remove all pound chars 
h        # copy pattern space to hold space 
d        # delete pattern space and start over 
}        # end if 
:a        # create label "a" 
G        # append hold to pattern 
s/Linux\(.*\)\n\(.*\)/\2\1/ # replace Linux with contents of hold space 
ta        # if above replacement succeeded, go to "a" 
s/\n.*//      # remove replacement text and print pattern space 
' file.txt 

的一行,如果你可以使用;分隔命令:

sed '/^#.*#$/{s/#//g;h;d};:a;G;s/Linux\(.*\)\n\(.*\)/\2\1/;ta;s/\n.*//' file.txt 
+1

爲什麼'-n'開關? – potong 2012-04-03 22:45:35

+0

有趣的是,我曾經想過,如果沒有'-n'開關,它會在輸出開始時產生一個額外的換行符,但我只是再次測試它,輸出看起來正確。剛編輯我的答案將其刪除。 – 2012-04-03 23:30:41

3

你會更好的使用awk。考慮一下這個腳本:

awk '/^#/ {gsub("#", "", $0); txt=$0} {gsub("Linux", txt, $0); print}' file.txt 
+0

我想這樣做的背景下,的apache mod_sed指令,沒有我知道通過awk運行apache輸出的高性能方法。 – 2012-04-03 17:16:27