How do I preserve text to output all at once in a file in cmd?

Viewed 82

I would like to know if there is a function like to preserve the text formating (like spaces, line breaks) cause I am creating a .bat file the create another .bat file accordingly.

Now if I want to output text to create the 2nd .bat file I would echo 1 line at a time.

@ECHO OFF
SET file=output.bat
ECHO @ECHO OFF > %file%
ECHO ECHO HELLO >> %file%
ECHO PAUSE >> %file%
Pause

The method above is really inefficient so I would like to output it all at once.

So can I output the text like this?

ECHO "@ECHO OFF
ECHO HELLO
PAUSE">%file%

Thanks!

3 Answers

You could redirect a block of code at once

@ECHO OFF
SET file=output.bat
(
  ECHO @ECHO OFF
  ECHO ECHO HELLO
  ECHO PAUSE 
) > %file%

Another way is to use the multi line character ^, but then you need also an empty line after each text line

@ECHO OFF
SET "file=output.bat"
(
  ECHO @ECHO OFF^

  ECHO HELLO^

  PAUSE
) > "%file%"

An altenative to Jebs solution is to use a prefix string and a for /f loop with findstr to read the text to be output to your secondary file.

@ECHO OFF & CD /d "%~dp0"
(
 For /f "tokens=1,* Delims=#" %%G in ('%__APPDIR__%findstr.exe /bl ":-#" "%~f0"')Do Echo(%%H
)>"outfile.bat"
outfile.bat

:-#@ECHO OFF
:-#ECHO HELLO
:-#PAUSE

Notes:

  • The Delim character cannot be present in text to be output. # is used as it's meaningless in batch syntax
  • The prefix string is always begun with : as this denotes a label and is disregarded by the interpreter when the batch runs.
  • an intermediary prefix character ( - in the above example ) allows multiple files to be stored in the source file. Simply change the prefix string in the findstr search term accordingly.
  • /bl ":-#" "%~f0" findstr searches the running batch "%~f0" for the literal string :-# at the beginning of each line.
  • variables will not be expanded
@ECHO OFF
SET file=output.bat
ECHO @ECHO OFF > %file%
ECHO ECHO HELLO >> %file%
ECHO PAUSE >> %file%
Pause

Can be replaced with limitations as

@ECHO @ECHO OFF ^& ECHO HELLO ^& PAUSE >output.bat
Related