如何使用批处理或PowerShell从文本文件中删除换行符 [英] How to remove newlines from a text file with batch or PowerShell
问题描述
基本上,我想从file.txt中读取内容
Essentially, I want to read from file.txt with contents
apple
banana
carrot
并写入newfile.txt,使其具有内容
and write to newfile.txt so that it will have contents
apple banana carrot
我需要在没有安装权限的Windows计算机上执行此操作.
I need to do this on a Windows computer on which I do not have install permissions.
我尝试了
set row=
for /f %%x in (file.txt) do set row=%row% %%x
echo row > newfile.txt
,我尝试使用PowerShell语句(无法运行PowerShell脚本)而不是CMD样式的for
循环.
and I tried using PowerShell statements (I cannot run PowerShell scripts) instead of the CMD-style for
loop.
powershell -Command "(Gc file.txt) | Foreach-Object -Process {set row=%row% _$} | Out-File newFile.txt"
,但是都产生一个空文件. 有办法吗?
but both produce an empty file. Is there a way to do this?
推荐答案
Get-Content
以包含换行符的行数组形式返回文件的内容,因此(在PowerShell中)您要做的就是加入各行,并将结果写回到文件中:
Get-Content
returns the content of a file as an array of lines with the line breaks already removed, so all you need to do (in PowerShell) is to join the lines and write the result back to a file:
(Get-Content 'input.txt') -join ' ' | Set-Content 'output.txt'
不推荐,但是如果必须批量执行此操作,则需要这样的内容:
Not recommended, but if you must do this in batch you need something like this:
@echo off
setlocal EnableDelayedExpansion
set row=
for /f %%x in (file.txt) do set "row=!row! %%x"
>newfile.txt echo %row%
请注意,需要延迟扩展才能正常工作.没有它,循环体中的%row%
会在解析时进行扩展(当变量仍为空时),因此循环结束后,您将只得到变量中输入文件的最后一行.启用延迟扩展(并使用!row!
而不是%row%
)后,变量将在运行时即通常在循环迭代期间进行扩展.
Note that delayed expansion is required for this to work. Without it %row%
in the loop body would be expanded at parse time (when the variable is still empty), so you'll end up with just the last line from the input file in the variable after the loop completes. With delayed expansion enabled (and using !row!
instead of %row%
) the variable is expanded at run time, i.e. during the loop iterations as one would normally expect.
有关延迟扩展的更多信息,请参见 Raymond Chen的博客.
For further information on delayed expansion see Raymond Chen's blog.
这篇关于如何使用批处理或PowerShell从文本文件中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!