<p>I would like 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. </p>

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

<p>If I use</p>

<pre><code>sed s/#include/#include "newfile.h"\n#include/
</code></pre>

<p>it replaces all #includes. </p>

<p>Alternative suggestions to achieve the same thing are also welcome.</p>

```
```
# sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---
```
```
or, if you prefer:
Editor's note: works with
GNU
```
sed
```
only.
```
```
sed '0,/foo/s//bar/' file
```
```
Source