0

Using Powershell v2 called from a batch file, I want to replace each CRLF in a file with just an LF. If a file only has LF without any CR, then I want all the LF to be left alone.

I do not want a terminating CRLF in the resultant file, if possible.

I found this question here on Stack Overflow, that seems to be a close match, but it does not specify a Powershell version requirement, nor does it specify the other criteria above. Hence this question.

The accepted answer for that question recommends this code:

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

I slightly modified it, and adjusted it to work from within a batch file, to read:

powershell -Command "(Get-Content file1.txt) -join '`n' > file2.txt"

Unfortunately, this does not work. All LF's are converted to the string `n.

How can I get this to work?

2 Answers2

2

Those before me are right you should use "`n"

When using PowerShell I recommend executing it the following switches:
-noninteractive indicate you do not want to interact with the powershell
-NoProfile - speeds up the things considerably (skips loading profile)
-ExecutionPolicy Bypass - bypasses security issues if you are on companies environment

Edit:

Sorry about the mistake you mentioned. I now have PowerShell 2.0 testing facility.

The fixed your example (the mistake was that you have to escape the double quotes due to the powershell.exe interpreting them). This approach does not work completely as it leaves CRLF at the end of the file:

powershell.exe -noninteractive -NoProfile -ExecutionPolicy Bypass -Command "& {(Get-Content file_crlf.txt) -join \"`n\" > file_lfonly.txt};"

However, the completely correct solution needs different approach (via IO.file class):

powershell.exe -noninteractive -NoProfile -ExecutionPolicy Bypass -Command "& {[IO.File]::WriteAllText('file_lfonly.txt', ([IO.File]::ReadAllText('file_crlf.txt') -replace \"`r`n\", \"`n\"))};"

This completely converts your CRLF to LF. Just small piece of warning it converts to ASCII not Unicode (out of scope of this question).

All examples are now tested on PowerShell v2.0.50727.

tukan
  • 13,399
  • 1
  • 15
  • 39
0

A couple of things:

  • Single quotes ' are literal - use double quotes " so that PowerShell knows you mean new line

  • If you need to escape double quotes within double quotes, use "" or `"

Edit:

Your original post worked for me, so looks like this is related to PowerShell 5 v 2, and I am unable to test the solution. Instead of escape characters, here is a solution using scriptblock:

powershell -Command {(Get-Content file1.txt) -join "`n" > file2.txt}

It's worth noting that this is trivial in Notepad++ and can be done for multiple files at once:

New line replace in Notepad++

G42
  • 9,230
  • 2
  • 15
  • 33