59

我正在搜索(没有成功)一个脚本,它可以作为一个批处理文件工作,如果没有 BOM,我可以在 UTF-8 文本文件之前添加一个 BOM。

它所用的语言(perl、python、c、bash)和它所运行的操作系统对我来说都不重要。我可以使用各种计算机。

我发现很多脚本可以做相反的事情(剥离 BOM),这听起来有点傻,因为许多 Windows 程序如果没有 BOM 将无法读取 UTF-8 文本文件。

我错过了显而易见的事情吗?

谢谢!

4

7 回答 7

50

我使用 '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

编辑:mv在参数周围添加引号。谢谢@DirkR,很高兴这个脚本很有帮助!

于 2010-07-20T19:58:34.237 回答
49

我为此找到的最简单的方法是

#!/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

我知道它使用外部程序(cat)......但它会在 bash 中轻松完成这项工作

在 osx 上测试过,但也应该在 linux 上工作

请注意,它假定文件还没有 BOM (!)

于 2016-05-24T22:48:22.517 回答
23

(答案基于yingted的https://stackoverflow.com/a/9815107/1260896 )

要将 BOM 添加到以“foo-”开头的所有文件中,您可以使用sed. sed可以选择进行备份。

sed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' foo-*

如果您确定已经没有 BOM,则可以简化命令:

sed -i '1s/^/\xef\xbb\xbf/' foo-*

确保需要设置 UTF-8,因为 即 UTF-16 不同(否则检查How can I re-add a unicode byte order marker in linux?

于 2016-03-04T22:19:28.127 回答
17

作为对 Yaron U. 解决方案的改进,您可以在一行中完成所有操作:

printf '\xEF\xBB\xBF' | cat - source.txt > source-with-bom.txt

cat -位表示连接到source.txt从 print 命令输入的内容的前面。在 OS X 和 Ubuntu 上测试。

于 2018-11-06T02:05:00.917 回答
3

我觉得很简单。假设文件总是UTF-8(你没有检测到编码,你知道编码):

阅读前三个字符。将它们与 UTF-8 BOM 序列进行比较(维基百科说它是 0xEF、0xBB、0xBF)。如果相同,请将它们打印到新文件中,然后将其他所有内容从原始文件复制到新文件中。如果不同,首先打印 BOM,然后打印三个字符,然后再打印从原始文件到新文件的所有其他内容。

在 C 中,fopen/fclose/fread/fwrite 应该足够了。

于 2010-06-27T13:18:24.217 回答
0

我根据Steven R. Loomis的代码创建了一个脚本。 https://github.com/Vdragon/addUTF-8bomb

结帐https://github.com/Vdragon/C_CPP_project_template/blob/development/Tools/convertSourceCodeToUTF-8withBOM.bash.sh例如使用此脚本。

于 2014-06-23T09:08:09.297 回答
0

在 VBA 访问中:

    Dim name As String
    Dim tmpName As String
    
    tmpName = "tmp1.txt"
    name = "final.txt"

    Dim file As Object
    Dim finalFile As Object
    Set file = CreateObject("Scripting.FileSystemObject")

    Set finalFile = file.CreateTextFile(name)
 
    
    'Add BOM
    finalFile.Write Chr(239)
    finalFile.Write Chr(187)
    finalFile.Write Chr(191)
    
    'transfer text from tmp to final file:
    Dim tmpFile As Object
    Set tmpFile = file.OpenTextFile(tmpName, 1)
    finalFile.Write tmpFile.ReadAll
    finalFile.Close
    tmpFile.Close
    file.DeleteFile tmpName
于 2020-11-27T11:09:08.847 回答