简体   繁体   中英

sed awk replace lines with a pattern match

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.

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

I would use 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.

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

使用GNU sed:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM