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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With