使用perl更改段落的格式

时间:2014-06-20 02:50:03

标签: perl

我有一些段落在一行的末尾有返回。我不希望在行尾返回,我会让布局程序来处理。我想删除返回,并用空格替换它们。

问题在于我确实希望段落之间有回报。所以,如果连续多次返回(2,3等),我想保留两次返回。

这将允许有段落,之间有一个空行,但行的所有其他格式都将被删除。这将允许布局程序担心换行符,而不是像现在那样由一定数量的字符确定中断。

我想使用Perl来完成此更改,但我对其他方法持开放态度。

示例文字:

This is a test.
This is just a test.

This too is a test.
This too is just a test.

会变成:

This is a test. This is just a test.

This too is a test. This too is just a test.

这可以轻松完成吗?

2 个答案:

答案 0 :(得分:1)

使用perl单线程。用2替换2个或更多的换行符。删除所有单个换行符:

perl -0777 -pe 's{(\n{2})\n*|\n}{$1//" "}eg' file.txt > newfile.txt

切换

  • -0777:覆盖整个文件
  • -p:为输入文件中的每个“行”创建一个while(<>){...; print}循环。
  • -e:告诉perl在命令行上执行代码。

答案 1 :(得分:0)

我想出了另一种解决方案,并想解释你的正则表达式匹配的内容。

Matt@MattPC ~/perl/testing/8
$ cat input.txt
This is a test.
This is just a test.

This too is a test.
This too is just a test.



another test.
test.

Matt@MattPC ~/perl/testing/8
$ perl -e '$/ = undef; $_ = <>; s/(?<!\n)\n(?!\n)/ /g; s/\n{2,}/\n\n/g; print' input.txt
This is a test. This is just a test.

This too is a test. This too is just a test.

another test. test.

我基本上只是写了一个perl程序并将其捣碎成一个单行程序。它通常看起来像这样。

# First two lines read in the whole file
$/ = undef;
$_ = <>;

# This regex replaces every `\n` by a space
# if it is not preceded or followed by a `\n`
s/(?<!\n)\n(?!\n)/ /g;

# This replaces every two or more \n by two \n
s/\n{2,}/\n\n/g;

# finally print $_
print; 

perl -p -i -e 's/(\w+|\s+)[\r\n]/$1 /g' abc.txt

这里的部分问题是你所匹配的。 (\w+|\s+)匹配一个或多个单词字符,与[a-zA-Z0-9_] OR 一个或多个空格字符相同,与[\t\n\f\r ]相同。

这不会匹配您的输入,因为您不匹配句点,并且没有行只包含空格或仅包含字符(即使空行也需要两个空白字符才能匹配它,因为我们最后有[\r\n])。另外,两者都不匹配一段时间。