用 vim 查看文件的格式和编码

在 Vim 中查看 .ps1 文件的 换行格式(CRLF/LF)编码(UTF-8/BOM),主要使用以下几个命令。


1. 查看换行格式(CRLF / LF)

打开文件:

vim install.ps1

进入 Vim 后:

:set fileformat?

输出:

Windows 格式:

fileformat=dos

表示:

CRLF (\r\n)

Unix 格式:

fileformat=unix

表示:

LF (\n)

Mac 老格式:

fileformat=mac

表示:

CR (\r)

现在基本不用。


2. 查看文件编码

Vim:

:set fileencoding?

例如:

fileencoding=utf-8

表示:

UTF-8

如果输出:

fileencoding=

表示 Vim 没有检测到特殊编码,通常使用:

utf-8

或者 Vim 默认编码。

查看 Vim 编码默认设置:

:set encoding?

例如:

encoding=utf-8

3. 查看是否有 BOM

BOM(Byte Order Mark):

UTF-8 BOM:

EF BB BF

Vim 查看:

:set bomb?

结果:

有 BOM:

bomb

表示:

UTF-8 with BOM

无 BOM:

nobomb

表示:

UTF-8 without BOM

4. 一次查看全部信息

推荐:

:set fileformat? fileencoding? bomb?

例如:

推荐状态:

fileformat=dos
fileencoding=utf-8
nobomb

对应:

换行:
CRLF

编码:
UTF-8

BOM:
无

这就是 Windows PowerShell 脚本最佳格式。


5. 查看不可见字符(最直观)

Vim:

:set list

例如:

CRLF:

Write-Host "hello"^M$

其中:

^M$

表示:

\r\n

LF:

Write-Host "hello"$

只有:

$

表示:

\n

关闭:

:set nolist

6. 在 Vim 中转换格式

LF → CRLF

执行:

:set fileformat=dos
:w

CRLF → LF

执行:

:set fileformat=unix
:w

7. 设置 UTF-8 无 BOM

转换:

:set encoding=utf-8
:set fileencoding=utf-8
:set nobomb
:w

8. 推荐检查 Claude Code 的 install.ps1

打开:

vim install.ps1

执行:

:set fileformat?
:set fileencoding?
:set bomb?

理想结果:

fileformat=dos
fileencoding=utf-8
nobomb

即:

✔ Windows CRLF
✔ UTF-8
✔ 无 BOM
✔ PowerShell 兼容性最佳

补充:如果你是在 Windows Git Bash 里的 Vim 查看,Vim 仍然可能显示 fileformat=unix,因为 Git Bash 默认偏向 Unix 行尾;这不代表文件一定不能运行,PowerShell 7 基本可以兼容。对于 Windows PowerShell 5.1 + 安装脚本,转换成 dos 更稳。

posted @ 2026-08-09 21:43  立体风  阅读(12)  评论(0)    收藏  举报