Pet*_*r.O 6 text-processing unicode wc
直接的想法是wc
,但接下来不是那么直接的想法是...... *nix 是否wc
纯粹用于 *nix 行结尾 \x0a?......似乎是这样。
我已经绕开了它,但我觉得可能/必须有一种比处理原始十六进制转储更简单的方法。
这是我的版本,但计数中仍然存在神秘的差异。 wc
报告0a
比此脚本CRLF
+的总和多 1 0a
。
file="nagaricb.nag"
echo Report on CR and LF in UTF-16LE/CR-LF
echo =====================================
cat "$file" | # a useles comment, courtesy of cat
xxd -p -c 2 |
sed -nr '
/0a../{
/0a00/!{
i ??`0a: embedded in non-newline chars
b
}
}
/0d../{
/0d00/!{
i ??`0d: embedded in non-newline chars
b
}
}
/0a00/{
i ??`CR: found stray 0a00
b
}
/0d00/{
N
/0d00\n0a00/{
i ??`CRLF: found as normal newline pairs
b
}
i ??`LF: found stray 0d00
}' |
sort |
uniq -c
echo " ====="
printf ' %s ??`wc\n' $(<"$file" wc -l)
Run Code Online (Sandbox Code Playgroud)
输出
Report on CR and LF in UTF-16LE/CR-LF
=====================================
125 ??`0a: embedded in non-newline chars
407 ??`0d: embedded in non-newline chars
31826 ??`CRLF: found as normal newline pairs
=====
31952 ??`wc
Run Code Online (Sandbox Code Playgroud)
有没有更标准/简单的方法来做到这一点?
我会将文件转换为带有 LF 行结尾的 UTF-8,因此我可以直接使用本机工具:
$ iconv -f UTF-16LE -t UTF-8 myfile.txt | dos2unix | wc -l
Run Code Online (Sandbox Code Playgroud)
这dos2unix
部分是最棘手的部分。这个工具有很多变种,并不是所有变种都知道如何在管道中使用。有时它被称为其他东西,例如d2u
.
这是一个 perl 脚本,它以 UTF-16(通过 BOM 检测到字节顺序)打开文件(作为命令行参数给出),并计算行数。
#! /usr/bin/env perl
use strict;
use warnings;
while (my $file = shift @ARGV) {
my $fh;
if (!open($fh, '<:encoding(UTF-16)', $file)) {
print STDERR "Failed to open [$file]: $!\n";
next;
}
my $count = 0;
$count++ while (<$fh>);
print "$file: $count\n";
close $fh;
}
Run Code Online (Sandbox Code Playgroud)
(如果不理解 BOM,就会死亡。)