1

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,497
  • 2
  • 27
  • 46

2 Answers2

4

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
  • 118,548
  • 33
  • 236
  • 227
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,908
  • 1
  • 23
  • 43