U-L
U-L

Reputation: 2681

replace \n with blank but keep \r\n using sed/tr

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.

Upvotes: 2

Views: 6445

Answers (4)

Juan Carlos
Juan Carlos

Reputation: 1

sed -z -i.bak 's/\n/\r\n/g' filename

Upvotes: 0

Abhinandan prasad
Abhinandan prasad

Reputation: 1079

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

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 0

John1024
John1024

Reputation: 113814

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.

Upvotes: 2

Related Questions