在脚本中通过 vim 将文件编码更改为 utf-8 [英] Change File Encoding to utf-8 via vim in a script

查看:37
本文介绍了在脚本中通过 vim 将文件编码更改为 utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的服务器从 Debian 4 更新到 5 后,我被击倒了.我们切换到 UTF-8 环境,现在我们无法在浏览器上正确打印文本,因为所有文件都采用非 utf8 编码,如 iso-8859-1、ascii 等.

I just got knocked down after our server has been updated from Debian 4 to 5. We switched to UTF-8 environment and now we have problems getting the text printed correctly on the browser, because all files are in non-utf8 encodings like iso-8859-1, ascii, etc.

我尝试了许多不同的脚本.

I tried many different scripts.

我尝试的第一个是iconv".那个不行,它改变了内容,但文件的编码仍然是非utf8.

The first one I tried is "iconv". That one doesn't work, it changes the content, but the file's encoding is still non-utf8.

我通过 apt-get 安装的 enca、encamv、convvv 和其他一些工具也有同样的问题.

Same problem with enca, encamv, convmv and some other tools I installed via apt-get.

然后我找到了一个 python 代码,它使用 chardet Universal Detector 模块来检测文件的编码(工作正常),但是使用 unicode 类或编解码器类将其保存为 utf-8 不起作用,没有任何错误.

Then I found a python code, which uses chardet Universal Detector module, to detect encoding of a file (which works fine), but using the unicode class or the codec class to save it as utf-8 doesn't work, without any errors.

我发现将文件及其内容转换为 UTF-8 的唯一方法是 vi.

The only way I found to get the file and its content converted to UTF-8, is vi.

这些是我为一个文件所做的步骤:

These are the steps I do for one file:

vi filename.php
:set bomb
:set fileencoding=utf-8
:wq

就是这样.那个完美无缺.但是我怎样才能通过脚本运行它呢?我想编写一个脚本(Linux shell),它遍历一个包含所有 php 文件的目录,然后使用 vi 和上面的命令转换它们.因为我需要启动 vi 应用程序,所以我不知道如何做这样的事情:

That's it. That one works perfect. But how can I get this running via a script? I would like to write a script (Linux shell) which traverses a directory taking all php files, then converting them using vi with the commands above. As I need to start the vi app, I do not know how to do something like this:

vi --run-command=':set bomb, :set fileencoding=utf-8' filename.php"

希望有人能帮助我.

推荐答案

这是我所知道的从命令行轻松完成此操作的最简单方法:

This is the simplest way I know of to do this easily from the command line:

vim +"argdo se bomb | se fileencoding=utf-8 | w" $(find . -type f -name *.php)

或者更好的是,如果预计文件数量非常大:

Or better yet if the number of files is expected to be pretty large:

find . -type f -name *.php | xargs vim +"argdo se bomb | se fileencoding=utf-8 | w"

这篇关于在脚本中通过 vim 将文件编码更改为 utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆