Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete newlines ('\n', 0x0A) from non-empty lines using tr(1)?

Tags:

bash

sed

perl

tr

I have a file named file1 with following content:

The answer t
o your question 

A conclusive a
nswer isn’t al
ways possible.

When in doubt, ask pe
ople to cite their so
urces, or to explain

Even if we don’t agre
e with you, or tell y
ou.

I would like to convert file1 into file2. Latter should look like this:

The answer to your question

A conclusive answer isn’t always possible.

When in doubt, ask people to cite their sources, or to explain

Even if we don’t agree with you, or tell you.

In case I simply execute cat file1 | tr -d "\n" > file2", all the newline characters will be deleted. Ho do delete only those newline characters, which are on the non-empty lines using the tr(1) utility?

like image 294
Martin Avatar asked Nov 18 '11 05:11

Martin


2 Answers

perl -00 -lpe 'tr/\n//d'

-00 is Perl's "paragraph" mode, reading the input with one or more blank lines as the delimiter. -l appends the system newline character to the print command, so it's safe to delete all newlines in the input.

like image 68
glenn jackman Avatar answered Oct 02 '22 04:10

glenn jackman


tr can't do this, but sed easily can

sed -ne '$!H;/^$/{x;s/\n//g;G;p;d;}' file1 > file2

This finds non-empty lines and holds them. Then, on empty lines, it removes newlines from the held data and prints the result followed by a newline. The held data is deleted and the process repeats.

EDIT:

Per @potong's comment, here's a version which doesn't require an extra blank line at the end of the file.

sed -ne 'H;/^$/{x;s/\n//g;G;p;};${x;s/\n//g;x;g;p;}' file1 > file2
like image 20
sorpigal Avatar answered Oct 02 '22 05:10

sorpigal