how to convert a file from DOS to Unix [closed]
Asked Answered
C

2

5

I need to convert a file from DOS to Unix in PowerShell.

I know this can be very much easily done in Unix:

dos2unix file newfile
Corinacorine answered 18/8, 2015 at 5:9 Comment(2)
Why not do the conversion in the *nix system? Or use Cygwin's tools for the same instead of re-inventing the wheel.Cr
Replace CRLF using powershellComorin
S
9

It could be as simple as

Get-Content in.csv -raw | % {$_ -replace "`r", ""} | Set-Content -NoNewline out.csv

Above method will work on powershell version 3+. If you are below that you can use below method instead. Almost same as one of the other answers here.

$csvdata = [io.file]::ReadAllText('in.csv') | % {$_ -replace "`r",""}
[io.file]::WriteAllLines('out.csv', $csvdata)
Start answered 18/8, 2015 at 5:57 Comment(2)
-NoNewline doesn't seem to exist.Byre
Updated my answer with a version that works pre v3.Start
B
3

Try this:

$txt = (Get-Content -Raw myFile.txt) -replace "`r`n","`n"
[io.file]::WriteAllText('c:\path\to\myFile.unix.txt', $txt)

I used WriteAllText rather than Set-Content because Set-Content adds a carriage return and a line feed to the end of the file, and there doesn't seem to be any way to suppress that.

I think that the -Raw parameter to Get-Content might be a PowerShell 3 thing, so if you are using an earlier version, you might need to do it like this:

$txt = [io.file]::ReadAllText('c:\path\to\myFile.txt') -replace "`r`n","`n"
[io.file]::WriteAllText('c:\path\to\myFile.unix.txt', $txt)
Byre answered 18/8, 2015 at 5:48 Comment(2)
Yes, the parameter -Raw exists only in PowerShell v3 and above. However, if you're writing with a .NET method I'd use a .NET method for reading anyway, if only for symmetry reasons.Cark
The first part worked like a charm!Schipperke

© 2022 - 2024 — McMap. All rights reserved.