简体   繁体   中英

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

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
"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM