sed awk用模式匹配替换行

时间:2015-05-04 17:44:42

标签: replace awk sed

使用awk或sed如何在模式匹配后替换每一行? 该模式总是以S:\和其他方式开始, 我需要从S:\〜到最后的整行出现在空白行之前的下一行。

我有这样的输入:

S:\dir1\subfolder1longsubf
abcdefg
1234567
permissions

S:\dir2\verylongsub
some random string
some random string

S:\dir3
some random string
some random string

S:\dir4\sub2\sub3
some random string
some random string
some random string

我需要这样的输出:

S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf

S:\dir2\verylongsub
S:\dir2\verylongsub
S:\dir2\verylongsub

S:\dir3
S:\dir3
S:\dir3

S:\dir4\sub2\sub3
S:\dir4\sub2\sub3
S:\dir4\sub2\sub3
S:\dir4\sub2\sub3

2 个答案:

答案 0 :(得分:3)

我会使用awk

awk '/^S/ {line=$0} {print NF?line:""}' file

这会存储以S开头的行。然后,如果该行为空,则打印该存储的值或空行。

测试

$ awk '/^S/ {line=$0} {print NF?line:""}' file
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf

S:\dir2\verylongsub
S:\dir2\verylongsub
S:\dir2\verylongsub

S:\dir3
S:\dir3
S:\dir3

S:\dir4\sub2\sub3
S:\dir4\sub2\sub3
S:\dir4\sub2\sub3
S:\dir4\sub2\sub3

答案 1 :(得分:2)

使用GNU sed:

sed  '/^S:/{h};/^[^S]/{g}' file