4

I'm trying to replace the first occurrence in a file using sed:

sed -i s/he/He/ dummy.txt

Instead of replacing first occurrence, it replaces all the occurrences, even without /g.

According to the documentation it should replace the first only.

The sed version which is:

GNU sed version 4.1.5

Am I missing anything? Or does the behavior differ for different sed implementations?

  • @StephenKitt Yeah. I have seen that link. But most of the tutorials or other sites mentioned that without /g sed will replace the first occurence only. So I'm getting different result due to version or something? – sathya_dev Jun 19 '15 at 9:24
  • sed is basically a line editor - it works on one line at a time (unless you program it to read more lines into its buffer (called the pattern space). Where you have seen "g will replace the first occurrence only" refers to the first occurrence in the current pattern space, ie. in the current line. – Peter.O Jun 19 '15 at 9:51
4

sed processes input line by line. The /g modifier influences whether it replaces all the occurrences on a line, or only the first one:

echo hehe | sed s/h/H/
echo hehe | sed s/h/H/g

To replace only the first occurrence in the file, use something like the following:

s/h/H/            # Replace.
ta                # Go to a if s/// worked.
b                 # Otherwise, start the next cycle.
:a { n            # Process the next line.
     ba           # Go to a.
}
  • That g thing is a real red herring. You'd think there would be some other option by now to differentiate line level "global" from the (non-existent) file level "global". – Dale Anderson Feb 4 '17 at 1:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.