如何确定文件编码?

3
有没有类似于Linux下的file命令返回文件编码的git命令?这完全描述了我的问题。我尝试在谷歌上搜索但没有找到任何有用的结果。

你已经尝试过什么了? - undefined
这与git有什么关系? - undefined
@MrTux 我想使用git命令获取文件的编码方式。这与git有什么关系? - undefined
1
请注意,file 命令只能猜测文件的编码方式。总体来说,无法完美地检测文件的编码方式。 - undefined
2个回答

11

Git本身对文件的编码没有概念(存储为blob,意味着任意的二进制数据)。
请参阅“git blob的格式是什么?”。

git checkout后仍可使用command file。
或者在git show之后将其作为管道命令,并读取特定文件的内容,例如:

$ git show @~2:README.md | file -
/dev/stdin: ASCII text

告诉我们2次提交之前的文件./README.md采用了ASCII编码 - 注意最后的短横线 (-) 代表标准输入。

而这个命令:

$ git show :README.md | file -
/dev/stdin: Unicode text, UTF-8 (with BOM) text, with CRLF line terminators

告诉我们,git的“索引”中的相同文件将会是Windows编码。


0

如果你想要转换行尾符(从CRLF(Windows)到Linux标准或其他),你可以尝试像这样的方法,由@VonC在这里回答。

或者如果你想要转换文件的编码(例如:从ISO-8859-1到UTF-8),并且你是一个Linux用户,你可以尝试像@Celada在这里回答的方法。

You can do this with
git filter-branch
The idea is that you have to change the encoding of the files in every commit, rewriting each commit as you go.
First, write a script that changes the encoding of every file in the repository. It could look like this:

    #!/bin/sh
    find . -type f -print | while read f; do
        mv -i "$f" "$f.recode.$$"
        iconv -f iso-8859-1 -t utf-8  "$f"
        rm -f "$f.recode.$$"
    done
Then use
git filter-branch
to run this script over and over again, once per commit:
git filter-branch --tree-filter /tmp/recode-all-files HEAD
where /tmp/recode-all-files is the above script.
Right after the repository is freshly upgraded from CVS, you probably have just one branch in git with a linear history back to the beginning. If you have several branches, you may need to enhance the git filter-branch command to edit all the commits."

是的,我已经找到了这个,但这不是我想要的。我只是想用git获取文件编码。当然,我可以像我在问题中指出的那样使用bash命令来做到这一点。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接