unix sed substitute nth occurence misfunction?

前端 未结 3 417
抹茶落季
抹茶落季 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条回答
  •  后悔当初
    2021-01-24 19:33

    Below sed works closely to what you are looking for, except it removes also the last Z.

    $echo aaZbbZccZdd | sed -e 's/Z[^Z]*//1g;s/$/Z/'
    aaZ
    
    $echo aaZbbZccZdd | sed -e 's/Z[^Z]*//2g;s/$/Z/'
    aaZbbZ
    
    $echo aaZbbZccZdd | sed -e 's/Z[^Z]*//3g;s/$/Z/'
    aaZbbZccZ
    
    $echo aaZbbZccZdd | sed -e 's/Z[^Z]*//4g;s/$/Z/'
    aaZbbZccZddZ
    

    Edit: Modified according to Aaron suggestion.

    Edit2: If you don't know how many Z there are in the string it's safer to use below command. Otherwise additional Z is added at the end.
    -r - enables regular expressions
    -e - separates sed operations, the same as ; but easier to read in my opinion.

    $echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//1g' -e 's/([^Z])$/\1Z/'
    aaZ
    
    $echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//2g' -e 's/([^Z])$/\1Z/'
    aaZbbZ
    
    $echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//3g' -e 's/([^Z])$/\1Z/'
    aaZbbZccZ
    
    $echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//4g' -e 's/([^Z])$/\1Z/'
    aaZbbZccZddZ
    
    $echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//5g' -e 's/([^Z])$/\1Z/'
    aaZbbZccZddZ
    

提交回复
热议问题