Ste*_*ane 42 scripting byte-order-mark batch-file utf-8
我正在搜索(没有成功)一个脚本,它可以作为一个批处理文件使用,如果它没有,我可以在它前面添加一个带有BOM的UTF-8文本文件.
它所写的语言(perl,python,c,bash)和它所使用的操作系统都不重要.我可以使用各种计算机.
我发现有很多脚本可以反向(剥离BOM),这听起来有些愚蠢,因为许多Windows程序如果没有BOM,就会无法读取UTF-8文本文件.
我错过了明显的吗?
谢谢!
Ste*_*mis 45
我使用'file'命令和ICU的'uconv'命令编写了这个addbom.sh .
#!/bin/sh
if [ $# -eq 0 ]
then
echo usage $0 files ...
exit 1
fi
for file in "$@"
do
echo "# Processing: $file" 1>&2
if [ ! -f "$file" ]
then
echo Not a file: "$file" 1>&2
exit 1
fi
TYPE=`file - < "$file" | cut -d: -f2`
if echo "$TYPE" | grep -q '(with BOM)'
then
echo "# $file already has BOM, skipping." 1>&2
else
( mv "${file}" "${file}"~ && uconv -f utf-8 -t utf-8 --add-signature < "${file}~" > "${file}" ) || ( echo Error processing "$file" 1>&2 ; exit 1)
fi
done
Run Code Online (Sandbox Code Playgroud)
编辑:在mv参数周围添加引号.谢谢@DirkR,很高兴这个脚本非常有用!
Yar*_* U. 30
我找到的最简单的方法是
#!/usr/bin/env bash
#Add BOM to the new file
printf '\xEF\xBB\xBF' > with_bom.txt
# Append the content of the source file to the new file
cat source_file.txt >> with_bom.txt
Run Code Online (Sandbox Code Playgroud)
我知道它使用外部程序(cat)......但它会在bash中轻松完成
在osx上测试过但也应该在linux上运行
请注意,它假定该文件尚未包含BOM(!)
Fra*_*iat 12
(答案基于/sf/answers/687057521/ by yingted)
要将BOM添加到以"foo-"开头的所有文件,您可以使用sed.sed可以选择进行备份.
sed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' foo-*
Run Code Online (Sandbox Code Playgroud)
如果您确定已经没有BOM,则可以简化命令:
sed -i '1s/^/\xef\xbb\xbf/' foo-*
Run Code Online (Sandbox Code Playgroud)
确保你需要设置UTF-8,因为即UTF-16不同(否则检查如何在linux中重新添加unicode字节顺序标记?)
作为Yaron U.解决方案的改进,您可以在一行上完成所有操作:
printf '\xEF\xBB\xBF' | cat - source.txt > source-with-bom.txt
Run Code Online (Sandbox Code Playgroud)
该cat -位说是连接到source.txt从print命令输入的内容的最前面。在OS X和Ubuntu上测试。
我觉得很简单。假设文件始终是UTF-8(您没有检测编码,但您知道编码):
读出前三个字符。将它们与 UTF-8 BOM 序列进行比较(维基百科说它是 0xEF、0xBB、0xBF)。如果相同,则在新文件中打印它们,然后将原始文件中的其他所有内容复制到新文件中。如果不同,则首先打印 BOM,然后打印三个字符,然后才打印从原始文件到新文件的所有其他内容。
在C中,fopen/fclose/fread/fwrite应该足够了。