26

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.

jww
  • 97,681
  • 90
  • 411
  • 885
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

4 Answers4

36

Powered by mac in two Interpretation:

  1. echo foo | sed 's/f/f\'$'\n/'
  2. echo foo | gsed 's/f/f\n/g'
Max
  • 361
  • 1
  • 3
  • 2
24

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/'
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Kevin
  • 53,822
  • 15
  • 101
  • 132
0

...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
muet
  • 41
  • 4
  • 1
    Can you give more information about the mac osx version? I have this output `sed: 1: "2 i \\nSomeText\n\n": extra characters after \ at the end of i command` – Yohan W. Dunon Jul 05 '21 at 13:04
0

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

Harald Rudell
  • 787
  • 6
  • 7