Question:
Essentially, I want to read from file.txt with contents
1 2 3 |
apple banana carrot |
and write to newfile.txt so that it will have contents
1 |
apple banana carrot |
I need to do this on a Windows computer on which I do not have install permissions.
I tried
1 2 3 4 |
set row= for /f %%x in (file.txt) do set row=%row% %%x echo row > newfile.txt |
and I tried using PowerShell statements (I cannot run PowerShell scripts) instead of the CMD-style for
loop.
1 2 |
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?
Answer:
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:
1 2 |
(Get-Content 'input.txt') -join ' ' | Set-Content 'output.txt' |
Not recommended, but if you must do this in batch you need something like this:
1 2 3 4 5 6 |
@echo off setlocal EnableDelayedExpansion set row= for /f %%x in (file.txt) do set "row=!row! %%x" >newfile.txt echo %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.
For further information on delayed expansion see Raymond Chen’s blog.