ynn
ynn

Reputation: 4817

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

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?

Upvotes: 3

Views: 2002

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84363

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.

Upvotes: 1

Related Questions