fold -s
gnuは末尾のスペースやその他の悪い動作を残していたので、私が作成した perl ソリューションでチャイムを鳴らすこともできます。このソリューションは、CRLF の行末を処理し、それらをすべて LF に変換しますが、タブやバックスペース、または埋め込まれたキャリッジ リターンなどを含むテキストを (適切に) 処理しません。テキストに最小限の変更を加えます。特に、単語を分割することはありません (変化しませんwc -w
)。行にスペースが 1 つしかない (および CR がない) テキストは変更されません(スペースが次のように置き換えwc -c
られるため)。 LF を挿入するのではなくLF)。
#!/usr/bin/perl
use strict;
use warnings;
my $WIDTH = 80;
if ($ARGV[0] =~ /^[1-9][0-9]*$/) {
$WIDTH = $ARGV[0];
shift @ARGV;
}
while (<>) {
s/\r\n$/\n/;
chomp;
if (length $_ <= $WIDTH) {
print "$_\n";
next;
}
@_=split /(\s+)/;
# make @_ start with a separator field and end with a content field
unshift @_, "";
push @_, "" if @_%2;
my ($sep,$cont) = splice(@_, 0, 2);
do {
if (length $cont > $WIDTH) {
print "$cont";
($sep,$cont) = splice(@_, 0, 2);
}
elsif (length($sep) + length($cont) > $WIDTH) {
printf "%*s%s", $WIDTH - length $cont, "", $cont;
($sep,$cont) = splice(@_, 0, 2);
}
else {
my $remain = $WIDTH;
{ do {
print "$sep$cont";
$remain -= length $sep;
$remain -= length $cont;
($sep,$cont) = splice(@_, 0, 2) or last;
}
while (length($sep) + length($cont) <= $remain);
}
}
print "\n";
$sep = "";
}
while ($cont);
}