使用Sed将字符串替换为从正则表达式获得的另一个字符串

时间:2012-04-03 16:46:58

标签: regex sed

我想用第一行#中的字符串替换字符串(在示例中为单词Linux)。

所以我想转:

#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 个答案:

答案 0 :(得分:3)

使用awk会更好。考虑一下这个脚本:

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

答案 1 :(得分: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