0

I am trying to replace line breaks, for which I want to use sed (please do not suggest alternative tools). To replace a line break by a string I am trying

sed 's/\n/string/g'

which does not work, at least on my system (bash on Ubuntu 12.04). However the following

sed 's/string/\n/g'

does replace all occurrences of string by a line break.

For instance, consider the following file

hello
there

sed 's/\n/ /g' file gives me the same:

hello
there

but sed 's/hello/hello\n/g' file gives me a line break:

hello

there

Could some body tell me why sed is able to write a new line with \n but not to read it?

Miguel
  • 7,277
  • 2
  • 26
  • 45

2 Answers2

3

sed works on lines of input, you can't replace newlines like that. You need to append lines of input to the pattern space.

sed ':a;$!N;s/\n/string/;ta' inputfile

would replace newlines with string.

devnull
  • 111,086
  • 29
  • 224
  • 214
0
 sed -n '1h;1!H;$x;s/\n/string/gp' YourFile

other method by loading first into buffer and change all at once at the end and print result

NeronLeVelu
  • 9,588
  • 1
  • 22
  • 41