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.
I'd be perfectly happy with a way in PowerShell to at least detect a Unix file.
It's easy do this for one single file, but I'm after something a bit more scalable (hence leaning towards a PowerShellish solution).
Converting from Linux to Windows Line Breaks You can use the sed command to convert the file fileLinux. txt to Windows line breaks: The -i option tells sed to write the results back to the input file. The s is sed's substitute command.
To input the ^M character, press Ctrl-v , and then press Enter or return . In vim, use :set ff=unix to convert to Unix; use :set ff=dos to convert to Windows.
Back to line endings The reasons don't matter: Windows chose the CR/LF model, while Linux uses the \n model. So, when you create a file on one system and use it on the other, hilarity ensues.
Converting using Notepad++ To write your file in this way, while you have the file open, go to the Edit menu, select the "EOL Conversion" submenu, and from the options that come up select "UNIX/OSX Format". The next time you save the file, its line endings will, all going well, be saved with UNIX-style line endings.
Here is the pure PowerShell way if you are interested.
Finding files with at least one Unix line ending (PowerShell v1):
dir * -inc *.txt | %{ if (gc $_.FullName -delim "`0" | Select-String "[^`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 } }
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.
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.
There is dos2unix and unix2dos in Cygwin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With