Using Raku (formerly known as Perl_6)
raku -e '.put for slurp.subst(:global, / \N <(\n)> \N /, " ");'
OR
raku -e '.put for lines.join("\n").subst(:global, / \N <(\n)> \N /, " ");'
The two lines of code above are identical except first example slurp
s in the whole file at once, while the second example lazily reads in lines
and (since lines
auto-chomps input) join
s them back together with \n
newlines. In both examples then a subst
itution is performed wherein \n
newlines surrounded by \N
non-newline characters are converted to single blank spaces (<(…)>
denotes capture markers).
The OP also asks for code to regularize multiple blank lines between "paragraphs". At the end of either code example above, a second subst
itution can be added which is .subst(/ \n**3..* /, "\n\n", :global);
. This takes occurrences of \n**3..*
two-or-more consecutive blank lines and regularizes them to \n\n
a single blank line. Be sure to join the two subst
method calls with a .
dot.
Sample Input:
One sentence.
Second sentence.
Third sentence; end of paragraph 1.
One sentence.
Second sentence; end of paragraph 2.
New section following two blank lines, first sentence.
Second sentence.
Third sentence.
Fourth sentence; end of new section a.k.a. paragraph 3.
Sample Output (using both subst
calls described above):
One sentence. Second sentence. Third sentence; end of paragraph 1.
One sentence. Second sentence; end of paragraph 2.
New section following two blank lines, first sentence. Second sentence. Third sentence. Fourth sentence; end of new section a.k.a. paragraph 3.
Finally, I feel Raku does a really good job offering alternatives to the examples above, such as using the split
routine to regularize \n
newlines. If all you want to do is compact paragraphs then use the simple code below to store your text:
raku -e '.raku.put for slurp.split(/ \n**2..* /, :skip-empty);'
Output:
"One sentence.\nSecond sentence.\nThird sentence; end of paragraph 1."
"One sentence.\nSecond sentence; end of paragraph 2."
"New section following two blank lines, first sentence.\nSecond sentence.\nThird sentence.\nFourth sentence; end of new section a.k.a. paragraph 3."
You can then restore individual "paragraphs" by prepending with put
, terminating the line with ;
semicolon, and running Raku again to restore each sentence back onto its own line.
https://raku.org
tr -d "\n"
.