如何检查文件是否有效UTF-8?
-
02-07-2019 - |
解决方案
您可以使用GNU iconv:
$ iconv -f UTF-8 your_file -o /dev/null; echo $?
或者使用旧版本的iconv,例如在macOS上:
$ iconv -f UTF-8 your_file > /dev/null; echo $?
如果文件可以成功转换,该命令将返回0,否则返回1。此外,它将打印出无效字节序列发生的字节偏移量。
编辑:不必指定输出编码,它将被假定为UTF-8。
其他提示
使用python和str.encode |解码函数。
>>> a="γεια"
>>> a
'\xce\xb3\xce\xb5\xce\xb9\xce\xb1'
>>> b='\xce\xb3\xce\xb5\xce\xb9\xff\xb1' # note second-to-last char changed
>>> print b.decode("utf_8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 6: unexpected code byte
抛出的异常在其.args属性中请求信息。
>>> try: print b.decode("utf_8")
... except UnicodeDecodeError, exc: pass
...
>>> exc
UnicodeDecodeError('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
>>> exc.args
('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
您可以使用 isutf8 .name / code / moreutils /“rel =”noreferrer“> moreutils collection。
$ apt-get install moreutils
$ isutf8 your_file
在shell脚本中,使用 - quiet
开关并检查退出状态,对于有效的utf-8文件,该状态为零。
不隶属于 StackOverflow