With awk or sed how could I replace each line after a pattern match? the pattern would always start as S:\ and something else, I need the entire line from S:\~ to the end to appear on the next lines before a blank line.
使用awk或sed如何在模式匹配后替换每一行?模式总是以S:\和其他东西开始,我需要从S:\〜到最后的整行出现在空白行之前的下一行。
I have an input like this:
我有这样的输入:
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
and I need an ouput like this:
我需要这样的输出:
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 个解决方案
#1
I would use awk
:
我会用awk:
awk '/^S/ {line=$0} {print NF?line:""}' file
This stores the line starting with S
. Then, it prints either this stored value or an empty line if the line is empty.
这将存储以S开头的行。然后,如果该行为空,则打印此存储的值或空行。
Test
$ 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
#2
With GNU sed:
使用GNU sed:
sed '/^S:/{h};/^[^S]/{g}' file
#1
I would use awk
:
我会用awk:
awk '/^S/ {line=$0} {print NF?line:""}' file
This stores the line starting with S
. Then, it prints either this stored value or an empty line if the line is empty.
这将存储以S开头的行。然后,如果该行为空,则打印此存储的值或空行。
Test
$ 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
#2
With GNU sed:
使用GNU sed:
sed '/^S:/{h};/^[^S]/{g}' file