windows 使用 Powershell 的 UNIX 格式文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5102115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:15:49  来源:igfitidea点击:

UNIX format files with Powershell

windowsunixpowershellnewline

提问by aldrin

How do you create a unix file format in Powershell? I am using the following to create a file, but it always creates it in the windows format.

如何在 Powershell 中创建 unix 文件格式?我正在使用以下内容创建一个文件,但它总是以 windows 格式创建它。

"hello world" | out-file -filepath test.txt -append

As I understand, the new line characters CRLF make it to be a Windows format file whereas the unix format needs only a LF at the end of the line. I tried replacing the CRLF with the following, but it didn't work

据我了解,新行字符 CRLF 使其成为 Windows 格式文件,而 unix 格式只需要在行尾有一个 LF。我尝试用以下内容替换 CRLF,但没有用

"hello world" | %{ $_.Replace("`r`n","`n") } | out-file -filepath test.txt -append

采纳答案by Anders Zommarin

One ugly-looking answer is (taking input from dos.txt outputting to unix.txt):

一个难看的答案是(从 dos.txt 输出到 unix.txt 的输入):

[string]::Join( "`n", (gc dos.txt)) | sc unix.txt

but I would really like to be able to make Set-Content do this by itself and this solution does not stream and therefore does not work well on large files...

但我真的很希望能够让 Set-Content 自己做这件事,这个解决方案不能流式传输,因此在大文件上不能很好地工作......

And this solution will end the file with a DOS line ending as well... so it is not 100%

这个解决方案也会以 DOS 行结尾来结束文件......所以它不是 100%

回答by Andy Schneider

There is a Cmdlet in the PowerShell Community Extensionscalled ConvertTo-UnixLineEnding

PowerShell Community Extensions 中有一个 Cmdlet,名为 ConvertTo-UnixLineEnding

回答by evg656e

I've found that solution:

我找到了解决方案:

sc unix.txt ([byte[]][char[]] "$contenttext") -Encoding Byte

posted above, fails on encoding convertions in some cases.

上面发布,在某些情况下编码转换失败。

So, here is yet another solution (a bit more verbose, but it works directly with bytes):

所以,这是另一个解决方案(有点冗长,但它直接适用于字节):

function ConvertTo-LinuxLineEndings($path) {
    $oldBytes = [io.file]::ReadAllBytes($path)
    if (!$oldBytes.Length) {
        return;
    }
    [byte[]]$newBytes = @()
    [byte[]]::Resize([ref]$newBytes, $oldBytes.Length)
    $newLength = 0
    for ($i = 0; $i -lt $oldBytes.Length - 1; $i++) {
        if (($oldBytes[$i] -eq [byte][char]"`r") -and ($oldBytes[$i + 1] -eq [byte][char]"`n")) {
            continue;
        }
        $newBytes[$newLength++] = $oldBytes[$i]
    }
    $newBytes[$newLength++] = $oldBytes[$oldBytes.Length - 1]
    [byte[]]::Resize([ref]$newBytes, $newLength)
    [io.file]::WriteAllBytes($path, $newBytes)
}