问题描述
使用从批处理文件调用的Powershell v2,我想用LF替换文件中的每个CRLF.如果文件只有LF而没有任何CR,那么我希望所有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.
如果可能的话,我不想在结果文件中终止CRLF.
I do not want a terminating CRLF in the resultant file, if possible.
我在Stack Overflow上找到了这个问题,这似乎很匹配,但是它没有指定Powershell版本要求,也没有指定上面的其他条件.因此,这个问题.
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"
不幸的是,这不起作用.所有LF都转换为字符串 `n
.
Unfortunately, this does not work. All LF's are converted to the string `n
.
如何使它正常工作?
推荐答案
在我之前正确的人应该使用"`n"
Those before me are right you should use "`n"
使用PowerShell时,我建议执行以下开关:-noninteractive
表示您不想与Powershell交互-NoProfile
-大大加快操作速度(跳过加载配置文件)-ExecutionPolicy Bypass
-如果您在公司环境中,则绕过安全问题
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
对不起,您提到的错误.我现在有了PowerShell 2.0测试工具.
Sorry about the mistake you mentioned. I now have PowerShell 2.0 testing facility.
修复了您的示例(错误是由于powershell.exe解释了双引号,所以您必须转义双引号).这种方法不能完全起作用,因为它将CRLF
留在文件末尾:
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};"
但是,完全正确的解决方案需要不同的方法(通过IO.file类):
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\"))};"
这完全将您的CRLF
转换为LF
.只是一小段警告,它转换为ASCII而不是Unicode(超出了此问题的范围).
This completely converts your CRLF
to LF
. Just small piece of warning it converts to ASCII not Unicode (out of scope of this question).
所有示例现在都已在PowerShell v2.0.50727上进行了测试.
All examples are now tested on PowerShell v2.0.50727.
这篇关于Powershell v2:用LF替换CRLF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!