Why can we replace strings with sed by adding "g"?

Viewed 911

If you want to replace "abc" with "ABC" once a line, you will write

sed -e "s/abc/ABC/" <file name> #code1

And if you want to replace them for infinite times a line, you will write

sed -e "s/abc/ABC/g" <file name> #code2

What does this 'g' mean? I believe the code1 behaves like the below.

  1. The first line of the file is copied to the pattern space.
  2. "abc" in strings in the pattern space is replaced with "ABC".
  3. The replaced strings in the pattern space is displayed.
  4. The next line of the file is copied to the pattern space, and the process2 and process3 are repeated.

According to man sed, 'g' command means "Copy hold space to pattern space".

Now a question occurs. Isn't the hold space kept empty unless you copy the content of the pattern space? I understand 'g' copies hold space to pattern space, but I think hold space is always empty. Rather, I think you should write like

sed -e "hs/abc/ABC/g" <file name> #code3

where 'h' means "Copy pattern space to hold space", according to man sed.

I don't understand the behavior of hold space at all. Could anyone help me?

1 Answers
Related