古い記事
ランダムジャンプ
新しい記事
素の cut (-c) と fold コマンドは UTF-8 の文字列に対して途中で切っちゃうこともあって文字化けして困る。cut と fold のUTF8対応版が欲しい。

流石にネットのどこかにあるだろうと思って探してみたんだけど、探し方が悪かったのかすぐには見つからず。3分くらいがんばって調べてみたけど、こりゃ作った方が早いな、ということで車輪の再発明。

ざっくりと perl で書いています。

cut8 - UTF8対応cut

"-c" オプションのみ。
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use open ':utf8';
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";

my $cps_str = ""; # character positions
GetOptions("c=s" => \$cps_str);

my @cps = sort {_toint($a) <=> _toint($b)} split(/,/, $cps_str);
sub _toint {$_[0] =~ /^(\d+)/; $1}

while (<>) {
    chomp;
    my @c = split(//, $_);
    foreach my $cp (@cps) {
	if ($cp =~ /^(\d+)-(\d+)$/) {
	    print map {defined $_ ? $_ : ""} @c[($1-1)..($2-1)];
	} else {
	    print $c[$cp-1]||"";
	}
    }
    print "\n";
}
echo "あいうえおかきくけこ" | cut8 -c 1-3,7-9
あいうきくけ

fold8 - UTF8対応fold

"-w" オプションのみ。
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use open ':utf8';
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";

my $width = 80;
GetOptions("width=s" => \$width);

while (<>) {
    chomp;
    my $line = $_;
    if (length($line)) {
        while ($line =~ s/^(.{$width})//) {
            print "$1\n";
        }
        next if not length($line);
    }
    print "$line\n";
}
echo "あいうえおかきくけこ" | fold8 -w 4
あいうえ
おかきく
けこ

(追記190325: fold8 の空行が出ないバグを修正)