echo a for into a file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
thousandsword
Posts: 2
Joined: 06 Jul 2024 20:21

echo a for into a file?

#1 Post by thousandsword » 06 Jul 2024 20:31

Hello,

This is my first post in here, the question I have is if there is a possible way to echo a for into a file.

What I am trying to do is write a whole for loop into a new file to call it sometime later. The code kinda looks like this:
(
echo for /f "usebackq tokens=* delims=:" %%a in (`dir C:\myfolder\withmanyfiles\`) do (echo File inside My Folder is %%a)
) > "mybatchfile.bat"
The error message I get is "do was unexpected at this time", I know I could just use > to echo lines inside a file the for loop has more after the do and I thought it was easier to just write it then echo it into a file.

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: echo a for into a file?

#2 Post by jeb » 15 Jul 2024 01:34

Hi thousandsword,

the problem is that all characters after the ECHO are still parsed and that results in this error.

The first problem are the closing parentheses, but you can escape them with carets

Code: Select all

(
echo for /f "usebackq tokens=* delims=:" %%a in (`dir C:\myfolder\withmanyfiles\`^) do (echo File inside My Folder is %%a^)
) > "mybatchfile.bat" 
The next problem will be the percent signs, to write a single percent sign you need to double it.

Code: Select all

(
echo for /f "usebackq tokens=* delims=:" %%%%a in (`dir C:\myfolder\withmanyfiles\`^) do (echo File inside My Folder is %%%%a^)
) > "mybatchfile.bat" 

Compo
Posts: 600
Joined: 21 Mar 2014 08:50

Re: echo a for into a file?

#3 Post by Compo » 25 Aug 2024 09:46

Your extension .bat should really be .cmd, and the content of that file should ideally read as:

Code: Select all

@For /F "EOL=? Delims=" %%G In ('Dir "C:\myfolder\withmanyfiles" /A:-D /B 2^>NUL') Do @Echo File inside My Folder is %%G
This however introuces an additional problem, it includes another character which also requires handling.

To achieve the task now from another batch file, you'd need to escape some of the nested characters. In this case those characters are %, ^, and ).
I have done that below.

Code: Select all

@(
	Echo @For /F "EOL=? Delims=" %%%%G In ('Dir "C:\myfolder\withmanyfiles" /A:-D /B 2^^^>NUL'^) Do @Echo File inside My Folder is %%%%G
) 1>"mybatchfile.cmd"
I will leave it for you to work out what I did, to escape each of those characters and why.

thousandsword
Posts: 2
Joined: 06 Jul 2024 20:21

Re: echo a for into a file?

#4 Post by thousandsword » 31 Aug 2024 20:48

Thank you very much to both of you guys for taking the time to answer my question.

I will try both of your solutions and see what which of your solutions I will end up implementing in my code.


Greets,
thousandswords

Post Reply