Sunday, June 30, 2019

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

Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...