Home > Blockchain >  sed 'a' (append) doesn't work on OSX, and simply replaces line?
sed 'a' (append) doesn't work on OSX, and simply replaces line?

Time:12-29

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
"

CodePudding user response:

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.

  • Related