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

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

问题描述

是否有人知道Windows中可以递归目录并将所有UNIX文件转换为Windows文件的方法(例如Powershell或工具).

Does anyone know of 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 atleast one UNIX line ending (PowerShell v1):

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

这是查找和隐藏UNIX行尾并将其隐蔽到Windows行尾的方法.需要注意的重要一件事是,如果还没有结尾的行,则会在文件末尾添加一个额外的结尾(\ r \ n).如果您真的不想这样做,我将举一个如何避免它的示例(这有点复杂).

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 (\r\n) 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会自动将\ n上的内容分割(如果存在则删除\ r),然后在将每件事(在本例中为一行)写入文件时添加\ r \ n.这就是为什么您总是总是以文件末尾结尾的行的原因.

The above works because PowerShell will automatically split the contents on \n (dropping \r if they exist) and then add \r\n 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天全站免登陆