Skip to content
Advertisement

Problem inserting on first match only using GNU sed

4 on my linux machine (I checked w/ sed --version).

Currently, I have a myfile.txt with the following content:

---
title: hello
author: Jan King
foo: bar
author: Jan King
---

I know in GNU sed, I can append after the first occurrence of a match if I prepend the sed command with 0,.

So, if I want to insert goodbye after the first occurrence of ---, I can do that:

 sed -i '0,/---/a goodbye' myfile.txt

expected/correct result:

---
goodbye
title: hello
author: Jan King
foo: bar
author: Jan King
---

But now, I am trying to insert goodbye after the first occurrence of author: Jan King.

However, the following sed command doesn’t work and appends goodbye 3 times, which is not what I want:

 sed -i '0,/^author:.*/a goodbye' myfile.txt

incorrect/unexpected result:

---
goodbye
title: hello
goodbye
author: Jan King
goodbye
foo: bar
author: Jan King
---

If I remove 0, from the above sed command, then goodbye is appended twice after author: Jan King:

 sed -i '/^author:.*/a goodbye' myfile.txt

expected result:

---
title: hello
author: Jan King
goodbye
foo: bar
author: Jan King
goodbye
---

So I’m having trouble appending goodbye on first match only of author: Jan King (even though it is fine on first match of ---).

Can someone please explain why my sed command isn’t working? And how to fix it?

Advertisement

Answer

The link you show in the comment is not quite the same command sequence that you’re trying to use. If you want to use the same technique, try:

sed -i '0,/^(author:.*)/s//1nNew Inserted Line/' myfile.txt
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement