Issue
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.
Solution
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.
Answered By - John1024 Answer Checked By - Terry (WPSolving Volunteer)