删除新行,除非前面有特定字符集

Remove new lines except when preceded by specific set of characters

如何在 bash 命令行中使用 Perl 和/或 Sed 删除新行但避免使用特定字符集?

我最接近的是:

perl -C -i -p -e 's/[^.:]\n//' ~/Desktop/bak2

上面的代码在避免删除以点或冒号结尾的行方面运行良好,但它失败了,因为在删除正确的新行时它也会删除字符串的最后一个字符。我还需要将删除的 \n 替换为 space.

如果可能的话,Perl 和 Sed 都能提供这个解决方案,那就太好了。 我在 perl 或 sed 中搜索了类似的解决方案,但我没有找到它,如果它确实存在,我很抱歉。

示例:

现有内容:

Violets are blue and

Buda has great teachings.

Programming can be easy because:

Whosebug exists,

and the community always helps

a lot.

期望的输出:

Violets are blue and Buda has great teachings.

Programming can be easy because:

Whosebug exists, and the community always helps a lot.

您可以保留 new-line 之前的匹配(我添加了 "empty" 行处理):

perl -C -i -p -e 's/(^|[^.:])\n//' ~/Desktop/bak2

或使用正向后视

perl -C -i -p -e 's/(?<=[^.:])\n//' ~/Desktop/bak2
perl -i pe 's/[^.:]\K\n/ /' ~/Desktop/bak2

使用 sed

sed -e ':A;/[^.:]$/{N;bA' -e '};y/\n/ /' ~/Desktop/bak2

或 gnu sed

sed -z 's/\([^.:]\)\n/ /g' ~/Desktop/bak2