【问题标题】:How to write DOS line endings to a file from Unix如何从 Unix 将 DOS 行结尾写入文件
【发布时间】:2016-05-09 16:40:15
【问题描述】:

我的 Unix Ruby 程序需要编写一个文件,该文件将被 SqlServer 在 Windows 上运行。我需要我写给这个的行 文件以 \r\n 结尾,DOS/Windows 行结尾,而不是 \n, Unix 行结尾。我希望这发生在我不必 手动将 \r 添加到每行的末尾。

起点

如果我的程序这样写入文件:

File.open("/tmp/foo", "w") do |file|
  file.puts "stuff"
end

然后文件有 Unix 行结尾:

$ od -c foo
0000000   s   t   u   f   f  \n

这是意料之中的,因为我的程序是在 Unix 上运行的。但是我 需要这个文件(并且只有这个文件)有 DOS 行结尾。

手动将 \r 添加到每一行

如果我手动将 \r 添加到每一行:

File.open("/tmp/foo", "w") do |file|
  file.puts "stuff\r"
end

那么文件有 DOS 行结尾:

$ od -c /tmp/foo
0000000   s   t   u   f   f  \r  \n

这行得通,但必须为我想写的每一行重复。

使用字符串#encode

this SO answer所示,我可以使用修改字符串 写之前的String#encode:

File.open("/tmp/foo", "w") do |file|
  file.puts "alpha\nbeta\n".encode(crlf_newline: true)
end

这会导致 DOS 行结束:

$ od -c /tmp/foo
0000000   a   l   p   h   a  \r  \n   b   e   t   a  \r  \n

这样做的好处是,如果我一次写多行, 一次调用#encode 将更改该行的所有行尾 写。但是,它很冗长,我仍然必须指定行 每次写入都结束。

如何使每个puts 在 Unix 中打开文件 结束 Windows \r\n 中的行结尾而不是 Unix '\n' 行尾?

我正在运行 Ruby 2.3.1。

【问题讨论】:

    标签: ruby windows file unix encoding


    【解决方案1】:

    对此有一个选项,您在 encode 上使用的相同选项也适用于 File.open

    File.open('/tmp/foo', mode: 'w', crlf_newline: true) do |file|
      file.puts("alpha")
      file.puts("beta")
    end
    

    此选项不仅在\r\n 中结束行,它还将任何显式\n 转换为\r\n。所以这个:

    file.puts("alpha\nbar")
    

    会写alpha\r\nbar\r\b

    【讨论】:

    • 注意crlf_newline 选项也适用于Tempfile
    最近更新 更多