codereviewanskquestions
codereviewanskquestions

Reputation: 14008

How to add new line using sed on MacOS?

I wanted to add a new line between </a> and <a><a>

</a><a><a>

</a>
<a><a>

I did this

sed 's#</a><a><a>#</a>\n<a><a>#g' filename but it didn't work.

Upvotes: 26

Views: 26577

Answers (4)

Harald Rudell
Harald Rudell

Reputation: 837

on macOS 13.5 Ventura, 2023, this works:

sed -i '' '2i\'$'\n''line 2'$'\n' x

Which insert a line 2 into the existing file x, this new line containing “line 2”

  1. $'\n' is how a newline is typed on macOS
  2. two single-quoted strings next to each other are merged into one by bash/zsh
  3. the back-slash newline sequence is required by sed command i

Best operating system in the world according to Apple

Upvotes: 0

Kevin
Kevin

Reputation: 56129

Some seds, notably Mac / BSD, don't interpret \n as a newline, you need to use an actual newline, preceded by a backslash:

$ echo foo | sed 's/f/f\n/'
fnoo
$ echo foo | sed 's/f/f\
> /'
f
oo
$ 

Or you can use:

echo foo | sed $'s/f/f\\\n/'

Upvotes: 24

muet
muet

Reputation: 51

...or you just pound on it! worked for me on insert on mac / osx:

  sed "2 i \\\n${TEXT}\n\n" -i ${FILE_PATH_NAME}
  sed "2 i \\\nSomeText\n\n" -i textfile.txt

Upvotes: 0

Max
Max

Reputation: 361

Powered by mac in two Interpretation:

  1. echo foo | sed 's/f/f\'$'\n/'
  2. echo foo | gsed 's/f/f\n/g'

Upvotes: 36

Related Questions