0

I understand sed will

  1. Applies all instructions on line 1, then line 2...
  2. Previous instructions may change the pattern space so the next instruction will operate on that modified pattern space (instead of the original text)

The example is:

sample.txt file

pig cow

Command

sed -e 's/pig/cow/; s/cow/horse/;' sample.txt

Expected Output

horse horse

Real Output

horse cow

The reason for my expected output is:

  1. First instruction substituted pig with cow in the pattern space
  2. Second instruction substituted 2 pigs with 2 horses in the pattern space
  • Thank you, I forgot the g flag to apply the instruction on the whole line. If you could post this as an answer, I would gladly mark it as the solution. – Tran Triet Oct 10 '18 at 06:29

1 Answers1

2

The substitution command s will by default only substitute the first match, unless some flag is used after the replacement end delimiter, as in

sed -e 's/pig/cow/g; s/cow/horse/g' <sample.txt

The g flag tells sed to repeat the substitution as many times as possible for any non-overlapping match of the regular expression.

Another set of flags for the s command (not applicable here though, but might be useful to know about) is the single digit flags, with which you may choose to substitute the nth match of the pattern, as in

sed -e 's/a/A/3'

The above would change the third a to an A on every line of input.

See the manual for sed (man sed) on your system for further information.

Kusalananda
  • 333,661