unix sed substitute nth occurence misfunction?

前端 未结 3 448
抹茶落季
抹茶落季 2021-01-24 19:07

Let\'s say I have a string which contains multiple occurences of the letter Z. For example: aaZbbZccZ. I want to print parts of that string, each time until the nex

3条回答
  •  梦毁少年i
    2021-01-24 19:40

    This should do what you expect (see comments) unless your string can contain line breaks:

    # -n will prevent default printing
    echo 'aaZbbZccZ' | sed -n '{
        # Add a line break after each 'Z'
        s/Z/Z\
    /g
        # Print it and consume it in the next sed command
        p
    }' | sed -n '{
        # Add only the first line to the hold buffer (you can remove it if you don't mind to see first blank line)
        1 {
            h
        }
        # As for the rest of the lines
        2,$ {
            # Replace the hold buffer with the pattern space
            x
            # Remove line breaks
            s/\n//
            # Print the result
            p
            # Get the hold buffer again (matched line)
            x
            # And append it with new line to the hold buffer
            H
        }'
    

    The idea is to break the string into multiples lines (each is terminated with Z), that will be processed one by one on the second sed command.

    On the second sed we use the Hold Buffer to remember previous lines, print the aggregated result, append new lines and each time remove the line breaks we previously added.

    And the output is

    aaZ
    aaZbbZ
    aaZbbZccZ
    

提交回复
热议问题