开发者

sed: Delete blank lines following line ending with a marker

开发者 https://www.devze.com 2023-04-12 10:22 出处:网络
How do I do this using sed? Input:Expected output: 1|1 2 MARKER|2 MARKER |3 MARKER |4 5 MARKER |6 3 MARKER|开发者_开发技巧

How do I do this using sed?

    Input:                         Expected output:
    1               |              1
    2 MARKER        |              2 MARKER
                    |              3 MARKER
                    |              4
                    |              
                    |              5 MARKER
                    |              6
                    |              
    3 MARKER        |   开发者_开发技巧           
                    |              7 MARKER
    4               |              8
                    |              9
    5 MARKER        |                      
    6               |               
                    |              
                    |              
    7 MARKER        |                      
                    |              
    8               |               
    9               |               

First I tried this: It doesn't work coz "# niether t or b work because d causes the script to break."

/MARKER$/ {
#   i -- Line with MARKER
:my_branch
#   i -- in branch
    # write current patt space to output and read next line to pattern space
    n
    # if non blank goto EO script
    /^$/! b
    # if blank line delete it
    /^$/ d
    # loop back for more blank lines.
    t my_branch
    # niether t or b work because d causes the script to break.
    b my_branch
}

then I tried this, which almost works :((( -- it doesn't remove the line between 3 and 4, which I think is because 3 is consumed during the processing of 2 and thus it's marker is missed.

/MARKER$/ {
#       i -- Line with MARKER
:my_branch
#   i -- in branch
    N
    s/MARKER\n/MARKER/
    t my_branch
    # I added the following but it doesn't help..
    /MARKER$/ b my_branch
}

there 4-5 other versions I tried, but none worked.

I did all this because I was trying to answer this question: replace two newlines to one in shell command line, so I started learning sed from http://sed.sourceforge.net/sed1line.txt and http://www.grymoire.com/Unix/Sed.html

IOW I know there are solutions using awk, perl etc but I just wanted to learn using sed.

Thanks.


see below, I think it is what you want: (it ran on my linux box with gnu sed)

kent$  cat t
1         
2 MARKER  






3 MARKER  

4         

5 MARKER  
6         


7 MARKER  

8         
9         

kent$  sed -r ':a;N;s/(.*MARKER)\s+(\n.*)/\1\2/;ba;' t
1         
2 MARKER
3 MARKER
4         

5 MARKER
6         


7 MARKER
8         
9    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号