Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

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?

like image 568
ynn Avatar asked Jul 02 '26 01:07

ynn


1 Answers

The Global Modifier

In this context, the g at the end of a pattern is a flag or modifier for the preceding expression, and pragmatically means "global replace (within the current pattern space)."

More formally, in BSD's sed(1) the flag says:

g       Make the substitution for all non-overlapping
        matches of the regular expression, not just the
        first one.

For example:

# Replace only the first match.
$ echo 12345 | sed 's/[[:digit:]]/0/'
02345

# Replace all matches in the pattern, e.g. [g]lobal replacement.
$ echo 12345 | sed 's/[[:digit:]]/0/g'
00000

There are certainly other ways to get this result with this rather contrived example, but the point is that the g-modifier means "global" within the current pattern.

Modifiers/Flags vs. Commands

The use of a substitution flag is in contrast to the g or G commands, which copy or append the hold space to the pattern space. Even though the flag and the command may look similar, they are generally used in different contexts, and have completely different behavior. It may seem confusing at first, but commands aren't associated directly with (nor do they modify) substitution expressions, which can help you tell them apart.

like image 117
Todd A. Jacobs Avatar answered Jul 05 '26 02:07

Todd A. Jacobs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!