1

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"

Kreganthus
  • 124
  • 5
  • 2
    you can use `echo 'one two three four five six' | cut -d' ' -f1-2,4,6-` for given sample... (note your wording doesn't match sample)... with `sed` you can use multiple subs `sed 's/pattern/sub/2'; s/pattern/sub/3` but have to be careful that `3` in second sub is actually `4th` as first sub wiped out one `pattern` – Sundeep Mar 16 '17 at 16:03
  • I fixed my sample – Kreganthus Mar 16 '17 at 16:12

1 Answers1

3

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.

potong
  • 55,640
  • 6
  • 51
  • 83