使用Powershell的UNIX格式文件

yquaqz18  于 2023-01-30  发布在  Unix
关注(0)|答案(4)|浏览(190)

如何在Powershell中创建unix文件格式?我正在使用下面的方法创建文件,但它总是以windows格式创建。

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

据我所知,新的行字符CRLF使它成为Windows格式的文件,而unix只需要在行尾有一个LF。我试着用下面的代码替换CRLF,但没有成功

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

nimxete21#

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

h22fl7wq

h22fl7wq2#

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

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

但我真的希望能够使集内容做这件事本身,这个解决方案不流,因此不工作,以及对大文件...
而且此解决方案也会以DOS行结尾来结束文件...所以它不是100%

deikduxw

deikduxw3#

我找到了解决办法:

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

在某些情况下,编码转换会失败。
因此,这里还有另一个解决方案(有点冗长,但它直接处理字节):

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)
}
4sup72z8

4sup72z84#

使你的文件在这 windows CRLF格式.然后转换所有行到Unix在新文件:

$streamWriter = New-Object System.IO.StreamWriter("\\wsl.localhost\Ubuntu\home\user1\.bashrc2")
$streamWriter.NewLine = "`n"
gc "\\wsl.localhost\Ubuntu\home\user1\.bashrc" | % {$streamWriter.WriteLine($_)}
$streamWriter.Flush()
$streamWriter.Close()

不是一行程序,但适用于所有行,包括EOF。新文件现在在Win11的记事本中显示为Unix。
删除原始文件&重命名新文件为原始,如果你喜欢:

ri "\\wsl.localhost\Ubuntu\home\user1\.bashrc" -Force
rni "\\wsl.localhost\Ubuntu\home\user1\.bashrc2" "\\wsl.localhost\Ubuntu\home\user1\.bashrc"

相关问题