0

I have this script in a .bat file which unifies all the lines of a .txt into one, deleting the newlines (/n):

@echo off
setlocal EnableDelayedExpansion
set row=
for /f %%x in (file.txt) do set "row=!row!%%x"
>newfile.txt echo %row%

And it works perfectly, but now I want it to run only if "file.txt" exists. Otherwise, it's always going to create an empty "newfile.txt" file. Then I tried with:

@echo off
if exist file.txt (
setlocal EnableDelayedExpansion
set row=
for /f %%x in (file.txt) do set "row=!row!%%x"
>newfile.txt echo %row%
)

But in "newfile.txt" the result is different: "ECHO is disabled".

I can do it with Powershell, but I want to do it with CMD and then unify it with other scripts in a single .bat file.

Thank you very much for your help.

Compo
  • 34,184
  • 4
  • 22
  • 36
Danii R
  • 11
  • 1
  • You've used a parenthesized block, which means within it, the variable named `row` is in multiple states, _(not defined, defined, and obviously modified)_, you should therefore still be using `echo !row!` not `echo %row%`. – Compo May 09 '21 at 17:07
  • also fully possible without `delayedexpansion` line1: `@set "row=" && @if exist file.txt for /f %%x in (file.txt) do @call @set "row=%%row%%%%x"` Line 2: `>newfile.txt echo %row%` – Gerhard May 09 '21 at 18:53

0 Answers0