1

I need to create a file with Linux line endings in a Windows command script.

The closest I can get so far is this PowerShell one-liner:

powershell.exe -Command "Get-ChildItem -File "D:\path\file.sh" | % { $x = get-content -raw -path $_.fullname; $x -replace [char[]](13),'' | set-content -path $_.fullname }"

This is so close to what I want... the fly in the ointment is that it adds an extra CR+LF at the end of the file! Any suggestions for how I can fix this, or alternative techniques? I can't install any additional software such as Cygwin or dos2unix as this is for a locked-down production environment.

PhilHibbs
  • 195
  • 1
  • 3
  • 13
  • Have a look at https://stackoverflow.com/a/19128003/2579220, the last comment mentions `Set-Content -NoNewline`. – mvw Jan 11 '18 at 09:59
  • I'm running v4, -NoNewline is not available. – PhilHibbs Jan 11 '18 at 13:35
  • The other way: *[Convert Unix line endings to Windows](https://superuser.com/questions/71507)* – Peter Mortensen Aug 29 '20 at 17:33
  • there are many solutions in the other duplicate that requires no 3rd party tool, did you even read it? like `` (Get-Content $file -Raw).Replace("`r`n", "`n") | Set-Content $path -Force `` – phuclv Aug 07 '21 at 01:36
  • @phuclv YOU didn't even read the post you're linking to... Firstly, that post is about the inverse operation than what OP is asking. Secondly, the comment precisely before yours already links this question. And this is not the first time I see you doing this. Stop being an absolute jerk to everyone on SO, and start paying attention to what you're interacting with... – adamency Jun 01 '22 at 17:12
  • @adamency you don't even know that it's an automatic message from stackexchange when closing questions? And yes it applies for the reverse direction as well, just exchange the replacement strings. Did you even read my previous comment? It was unfortunately messed up due to Markdown in comments but it works correctly – phuclv Jun 02 '22 at 02:27

2 Answers2

1

This could be what you need :

powershell.exe -noninteractive -NoProfile -ExecutionPolicy Bypass -Command "& {[IO.File]::WriteAllText('file_lfonly.txt', ([IO.File]::ReadAllText('file_crlf.txt') -replace \"`r`n\", \"`n\"))};"
Ramhound
  • 41,734
  • 35
  • 103
  • 130
Marwen
  • 11
  • 1
0

The most elegant solution I could find is:

((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file

taken from here

adamency
  • 300
  • 1
  • 7