Unix 换行符到 Windows 换行符(在 Windows 上) [英] Unix newlines to Windows newlines (on Windows)

查看:61
本文介绍了Unix 换行符到 Windows 换行符(在 Windows 上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows 中是否有一种方法(比如 PowerShell 或工具)可以递归遍历目录并将任何 Unix 文件转换为 Windows 文件.

Is there a way (say PowerShell, or a tool) in Windows that can recurse over a directory and convert any Unix files to Windows files.

我对 PowerShell 中至少检测 Unix 文件的方法非常满意.

I'd be perfectly happy with a way in PowerShell to at least detect a Unix file.

对单个文件执行此操作很容易,但我想要更具可扩展性的东西(因此倾向于使用 PowerShellish 解决方案).

It's easy do this for one single file, but I'm after something a bit more scalable (hence leaning towards a PowerShellish solution).

推荐答案

如果您有兴趣,这里是纯 PowerShell 方式.

Here is the pure PowerShell way if you are interested.

查找至少有一个 Unix 行结尾的文件 (PowerShell v1):

Finding files with at least one Unix line ending (PowerShell v1):

dir * -inc *.txt | %{ if (gc $_.FullName -delim "`0" | Select-String "[^`r]`n") {$_} }

以下是您如何查找 Unix 行结尾并将其转换为 Windows 行结尾的方法.需要注意的一件重要事情是,如果文件末尾还没有行结尾,则会在文件末尾添加一个额外的行结尾 ( ).如果你真的不想那样做,我会发布一个你可以如何避免它的例子(它有点复杂).

Here is how you find and covert Unix line endings to Windows line endings. One important thing to note is that an extra line ending ( ) will be added to the end of the file if there isn't already a line ending at the end. If you really don't want that, I'll post an example of how you can avoid it (it is a bit more complex).

Get-ChildItem * -Include *.txt | ForEach-Object {
    ## If contains UNIX line endings, replace with Windows line endings
    if (Get-Content $_.FullName -Delimiter "`0" | Select-String "[^`r]`n")
    {
        $content = Get-Content $_.FullName
        $content | Set-Content $_.FullName
    }
}

上述工作是因为 PowerShell 会自动拆分 上的内容(如果存在,则删除 ),然后在将每个内容(在本例中为一行)写入文件时添加 .这就是为什么你总是以文件结尾的行结束.

The above works because PowerShell will automatically split the contents on (dropping if they exist) and then add when it writes each thing (in this case a line) to the file. That is why you always end up with a line ending at the end of the file.

另外,我写了上面的代码,以便它只修改它需要的文件.如果您不关心这一点,您可以删除 if 语句.哦,请确保只有文件才能访问 ForEach-Object.除此之外,您可以在管道开始时进行任何您想要的过滤.

Also, I wrote the above code so that it only modifies files that it needs to. If you don't care about that you can remove the if statement. Oh, make sure that only files get to the ForEach-Object. Other than that, you can do whatever filtering you want at the start of that pipeline.

这篇关于Unix 换行符到 Windows 换行符(在 Windows 上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆