6

在 Windows PowerShell 中:

echo "string" > file.txt

在 Cygwin 中:

$ cat file.txt
:::s t r i n g

$ dos2unix file.txt
dos2unix: Skipping binary file file.txt

我想在文件中有一个简单的“字符串”。我该怎么做?即,当我说cat file.txt我只需要“字符串”作为输出时。我从 Windows PowerShell 中呼应,这是无法更改的。

4

3 回答 3

12

尝试echo "string" | out-file -encoding ASCII file.txt获取一个简单的 ASCII 编码的 txt 文件。

生成的文件比较:

echo "string" | out-file -encoding ASCII file.txt

将生成一个包含以下内容的文件:

73 74 72 69 6E 67 0D 0A (string..)

然而

echo "string" > file.txt

将生成一个包含以下内容的文件:

FF FE 73 00 74 00 72 00 69 00 6E 00 67 00 0D 00 0A 00 (ÿþs.t.r.i.n.g.....)

(字节顺序标记 FF FE 表示文件是 UTF-16 (LE)。UTF-16 (LE) 的签名 = 2 个字节:0xFF 0xFE 后跟 2 个字节对。xx 00 xx 00 xx 00 表示正常的 0-127 ASCII字符

于 2011-11-17T08:26:04.497 回答
6

这两个命令是等效的,因为它们都默认使用 UTF-16 编码:

echo "string" > file.txt
echo "string" | out-file file.txt

您可以将显式编码参数添加到后一种形式(如 jon Z 所示)以生成纯 ASCII:

echo "string" | out-file -encoding ASCII file.txt

或者,您可以使用set-content,默认情况下使用 ASCII 编码:

echo "string" | set-content file.txt

推论1:

想要在一行中将 unicode 文件转换为 ASCII?

只需使用这个:

get-content your_unicode_file | set-content your_ascii_file

可以缩写为:

gc your_unicode_file | sc your_ascii_file

推论2:

想要获得一个十六进制转储,以便您真正了解什么是 unicode 和什么是 ASCII?

使用 PowerShell.com 上提供的简洁的Get-HexDump函数。有了它,您可以检查生成的文件:

Get-HexDump file.txt

对于任何重要的事情,您可以指定要输出的列宽以及要处理的文件字节数,如下所示:

Get-HexDump file.txt -width 15 -bytes 150
于 2011-11-17T20:50:59.353 回答
0

PowerShell 创建带有字节顺序标记 (BOM) 的 Unicode UTF-16 文件。

Dos2unix 6.0 及更高版本可以读取 UTF-16 文件并将其转换为 UTF-8(默认 Cygwin 编码)并删除 BOM。6.0 之前的版本会将 UTF-16 文件视为二进制文件并跳过它们,如您的示例所示。

于 2013-01-29T18:14:25.937 回答