0

Having some problems having sed insert the two-character sequence \n. (I'm using bash to create some expect scripts). Anything that I try in a replace pattern ends up as an actual newline character.

I've tried:

sed s/<string>/'\\\\n'/
sed s/<string>/\\\\n/
sed s/<string>/\\n/

And pretty much any permutation that does or doesn't make any sense.

I need it to work with the bash and sed installed on a Mac.

Mahsum Akbas
  • 1,523
  • 3
  • 21
  • 38
rleechb
  • 11
  • 1

2 Answers2

1

sed s/<string>/'\\n'/ works for me with both the Lunix (GNU) and OS X (bsd) versions of sed:

$ echo aXb | sed s/X/'\\n'/
a\nb

sed s/<string>/\\\\n/ would also work. When bash sees \\ (outside of quotes), it treats it as a single escaped backslash, so \ is actually passed to the command. When it sees \\\\n, that's just two escaped backslashes followed by "n", so it passes \\n to the command. Then, when sed sees \\n, it also treats that as an escaped backslash followed by "n", so the replacement string winds up being \n. Since the "n" is always after any completed escape sequence, it's just treated as another character in the replacement string.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
0

pure code, single quoted

sed 's/Pattern/\\n/' YourFile

Shell interpreted, double quote

sed "s/Pattern/\\\\n/" YourFile
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43