Search code examples
sedstring-substitution

sed: Is there an option to substitute the Nth AND Mth occurrence of a match per line?


I believe I am asking about pattern flags.

I am familiar with the global pattern flag 'g'

sed 's/pattern/sub/g'

And I know I can substitute the Nth occurrence of a match by using a number.

sed 's/pattern/sub/2'

But suppose I wanted to substitute the Nth AND Mth match on a line.

Example: Remove the 3rd and 5th word of the following string

Input: "one two three four five six"

Output: "one two four six"


Solution

  • This might work for you (GNU sed):

    sed -r 's/\S+\s*//5;s///3' file
    

    This removes the fifth and then the third non-spaced followed by possible spaced groups of characters.

    N.B. The removal is reversed i.e. 5 then 3 so that the previous removal does not affect the next.