0

I want to run a Windows batch FOR loop on a text file and strip spaces from the resulting variable, and then output each modified variable into text file.

I think I will need to use enabledelayedexpansion for this, but I cannot get the proper syntax

Here is an example to reproduce:

(
echo Here is my first line
echo Here is my second line
echo Here is my third line
)>"textfile.txt"

FOR /F "delims=" %%G IN ('TYPE textfile.txt') DO (
    (
        ECHO @ECHO OFF
        ECHO ECHO PLEASE WAIT
        ECHO ECHO.
        ECHO "%%windir%%\system32\cscript" "%%windir%%\system32\script.vbs" -\\REMOTESERVER\%%G
    )>%%G.txt
)

This code works as expected and outputs 3 files:

Here is my first line.txt
Here is my second line.txt
Here is my third line.txt

Here is my first line.txt contains:

@ECHO OFF
ECHO PLEASE WAIT
ECHO.
"%windir%\system32\cscript" "%windir%\system32\script.vbs" \\REMOTESERVER\Here is my first line

Here is my second line.txt contains:

@ECHO OFF
ECHO PLEASE WAIT
ECHO.
"%windir%\system32\cscript" "%windir%\system32\script.vbs" \\REMOTESERVER\Here is my second line

and so on.

I now want to strip the spaces. I want the files to be named:

Hereismyfirstline.txt
Hereismysecondline.txt
Hereismythirdline.txt

and I want them to contain:

@ECHO OFF
ECHO PLEASE WAIT
ECHO.
"%windir%\system32\cscript" "%windir%\system32\script.vbs" \\REMOTESERVER\Hereismyfirstline

and so on.

To accomplish this, I think that I need to use enabledelayedexpansion and add:

SET variable=%%G
SET variable=!variable: =!

But I am unsure how to add that to the code to the FOR loop and convert my % variables to !

1 Answer 1

1
@echo off
setlocal enabledelayedexpansion
(
echo Here is my first line
echo Here is my second line
echo Here is my third line
)>"textfile.txt"

FOR /F "delims=" %%G IN ('TYPE textfile.txt') DO (
    set "var=%%G"
    set "var=!var: =!"
    (
        ECHO @ECHO OFF
        ECHO ECHO PLEASE WAIT
        ECHO ECHO.
        ECHO "%%windir%%\system32\cscript" "%%windir%%\system32\script.vbs" -\\REMOTESERVER\!var!
    )>!var!.txt
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.