I want to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task I normally use a small bash script with sed to re-write the file.

How do I get sed to replace just the first occurrence of a string in a file rather than replacing the every occurrence?

I think I prefer the 'or if you prefer' solution. It would also be good to explain the answers - and to make the answer address the question directly, and then generalize, rather than generalize only. But good answer.
–
Jonathan LefflerSep 29 '08 at 13:15

1

FYI for Mac users, you have to replace the 0 with a 1, so: sed '1,/RE/s//to_that/' file
–
mhostOct 5 '14 at 1:24

@mhost No, it will than replace if pattern is found in line #1 and not if pattern is at other line, but still is the first found pattern. PS it should be mention that this 0, only works with gnu sed
–
JotneOct 29 '14 at 8:59

Could somebody please explain the 'or if you prefeer' solution? I don't know where to put the "from" pattern.
–
Jean-Luc Nacif CoelhoFeb 2 at 18:44

How this script works: For lines between 1 and the first #include (after line 1), if the line starts with #include, then prepend the specified line.

However, if the first #include is in line 1, then both line 1 and the next subsequent #include will have the line prepended. If you are using GNU sed, it has an extension where 0,/^#include/ (instead of 1,) will do the right thing.

${nowms} is the time in milliseconds set by a Perl script, $counter is a counter used for loop control within the script, \ allows the command to be continued on the next line.

The file is read in and stdout is redirected to a work file.

The way I understand it, 1,/====RSSpermalink====/ tells sed when to stop by setting a range limitation, and then s/====RSSpermalink====/${nowms}/ is the familiar sed command to replace the first string with the second.

In my case I put the command in double quotation marks becauase I am using it in a Bash script with variables.

And what, pray tell, is a text file but a series of lines of text?
–
Jonathan LefflerSep 29 '08 at 13:20

2

Obviously a text file is a stream of characters delimited by newlines. I just think that awk is a better tool for the type of problem the person posting the question asked.
–
duffbeer703Sep 30 '08 at 4:57