2

My input looks like:

Line 1\n 
More Line 1\r\n
Line 2\n 
More Line 2\r\n

I want to produce

Line 1 More Line 1\r\n
Line 2 More Line 2\r\n

Using sed or tr. I have tried the following and it does not work:

sed -e 's/([^\r])\n/ /g' in_file > out_file

The out_file still looks like the in_file. I also have an option of writing a python script.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
U-L
  • 2,671
  • 8
  • 35
  • 50
  • Possible duplicate of [How can I replace a newline (\n) using sed?](https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed) – Avinash Raj Sep 12 '17 at 05:45

4 Answers4

2

Try:

sed '/[^\r]$/{N; s/\n/ /}' in_file

How it works:

  • /[^\r]$/

    This selects only lines which do not have a carriage-return before the newline character. The commands which follow in curly braces are only executed for lines which match this regex.

  • N

    For those selected lines, this appends a newline to it and then reads in the next line and appends it.

  • s/\n/ /

    This replaces the unwanted newline with a space.

Discussion

When sed reads in lines one at a time but it does not read in the newline character which follows the line. Thus, in the following, \n will never match:

sed -e 's/([^\r])\n/ /g'

We can match [^\r]$ where $ signals the end-of-the-line but this still does not include the \n.

This is why the N command is used above to read in the next line, appending it to the pattern space after appending a newline. This makes the newline visible to us and we can remove it.

John1024
  • 109,961
  • 14
  • 137
  • 171
1

Try This:

tr '\n' ' ' < file | sed 's/\r/\r\n/g'

It will print:

Line 1 More Line 1\r\n
Line 2 More Line 2\r\n
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Abhinandan prasad
  • 1,009
  • 7
  • 13
  • Thank you for the answer. This works. I accepted the earlier answer as it was posted first. – U-L Sep 12 '17 at 16:51
0

awk solution:

awk '{ if(!/\\r\\n$/){ sep=""; sub("\\\\n","",$0) } else sep=ORS; printf "%s%s",$0,sep }' file

The output (literally):

Line 1 More Line 1\r\n
Line 2 More Line 2\r\n
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0
sed -z -i.bak 's/\n/\r\n/g' filename
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49