Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

batch file - Powershell v2: Replace CRLF with LF

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:UsersabcDesktopFileabc.txt"
$out = "C:UsersabcDesktopFileabc-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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...