Question: I have been using this code, to replace the first occurrence of a pattern in a file:

```
sed "0,\#pattern#s##replacement#" input.txt > output.txt

```

To replace the first 5 occurrences of a pattern in a file, I used this:

```
sed "0,\#pattern#s##replacement#" input.txt > output1.txt
sed "0,\#pattern#s##replacement#" output1.txt > output2.txt
sed "0,\#pattern#s##replacement#" output2.txt > output3.txt
sed "0,\#pattern#s##replacement#" output3.txt > output4.txt
sed "0,\#pattern#s##replacement#" output4.txt > output5.txt
mv output5.txt output.txt

```

How can I more simply replace the first `n` appearances of a match with `sed`?

Answer: 
This is not really a natural job for `sed` (personally I'd used `awk`) but the following should work:

```
 sed '1{x;s/.*/00000/;x};/PATTERN/{x;s/0//;x;t1;b;:1;s/PATTERN/REPLACEMENT/}'

```

The length of the string of `0`s in the first `s` command is the number of replacements; I used `0` with the intention of generating the `sed` command as follows:

```
 sed "1{x;s/.*/$(printf %*d $COUNT 0)/;x};
     /$PATTERN/{x;s/0//;x;t1;b;:1;s/$PATTERN/$REPLACEMENT/}"

```

With Gnu `sed`, you can replace `t1;b;:1;` with `T;`

Here's the awk version:

```
 awk 'N&&sub(PAT,REPL){N--};1' N=5 PAT="pattern" REPL="replacement"

```
You can also consider perl:

```
perl -lpe 's#pattern#s##replacement# and $n++ if $n < 5' input

```