1

I'm trying to update a file by adding text to a new line after a matching line. Following the documentation here I should be able to do this:

$ seq 3 | sed '2a hello'
1
2
hello
3

However, on Mac OSX, this doesn't work. Firstly, because '2a hello' doesn't seem to be interpreted as a valid sed command. Converting this to "s/2/a hello/" resolves the sed error, but simply replaces 2 with a hello:

$ seq 3 | sed "s/2/a hello/"
1
a hello
3

Is there some other way to use the append command with Sed on Mac?

EDIT

In addition to the answer below, here's how you do it when searching for strings.

As an example, if my file was instead:

one 
two 
four

And I wanted to add 'three' between two and four, I'd do:

sed "/two/a\\
four
"
TrolliOlli
  • 909
  • 2
  • 10
  • 18
  • 1
    Your syntax is wrong. As you can see in [the specification](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html), you are missing the backslash and the newline. – Jörg W Mittag Dec 28 '22 at 17:50

1 Answers1

1

On OSX you should use multiline sed for this:

seq 3 | sed '2a\
hello
'

Output:

1
2
hello
3

PS: This command will work for gnu sed as well.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • how would this change if I was searching for a string? As an example, if I had an input file where instead of 1, 2, 3 it had "one, two, and three", how do I modify this to search for "two"? – TrolliOlli Dec 28 '22 at 17:58
  • 1
    Nevermind I figured it out, I'll edit this above – TrolliOlli Dec 28 '22 at 18:06