3

I need to create a batch file that writes a text file (possibly including variables). In Unix with bash this is trivial:

#!/bin/bash
ver="1.2.3"
cat > file.txt <<EOL
line 1, ${ver}
line 2 
line 3
... 
EOL

What is the simplest way to do this with a batch file?

Note: there is a complete solution using an 'heredoc' routine at heredoc for Windows batch? but it seems too complex for ad-hoc use. I'm looking for a quick and simple way.

Community
  • 1
  • 1
Dror Harari
  • 3,076
  • 2
  • 27
  • 25
  • Type in the batch file. –  Nov 06 '16 at 15:53
  • @SomethingDark - thanks, I tried to find it and could not. The heredoc is pretty complete though much more complex for ad-hoc cases. I found some other questions but I could not add the suggested answer to them so I opened a new one. Should I delete this? – Dror Harari Nov 06 '16 at 16:32
  • 2
    It's up to you, really. Personally, I would, but at the same time if we deleted all the batch questions that were duplicates of existing batch questions, there wouldn't have been any questions asked in 2016. – SomethingDark Nov 06 '16 at 16:34

2 Answers2

5

The follwoing works fine, if there is just one block of data (text)

@ECHO OFF
set string=beautyful
REM get linenumber for Data:
for /f "tokens=1 delims=:" %%a in ('findstr /n /b "REM StartData" "%~f0"') do set ln=%%a

REM print Data (use call to parse the line and evaluate variables):
(for /f "usebackq skip=%ln% delims=" %%a in ("%~f0") do call echo %%a)>"new.txt"
type "new.txt"
goto :eof

REM StartData
hello %string% world
line 2
line 3

If you don't have variables in the data, omit the call. Advantage: no need to escape anything. Even usually poisonous characters work (instead of the for loop, you can also just use more +%ln% "%~f0"). Sadly, you loose this advantage, when you use call to parse the lines for variables.

Stephan
  • 53,940
  • 10
  • 58
  • 91
2

The easiest and least messy way I found is as follows:

set ver=1.2.3
(
echo ^
line 1, %ver%^

line 2^

line 3^

...
) > file.txt

Running the script I get:

C:\> type file.txt
line 1, 1.2.3
line 2
line 3
...

Basically, each line must be terminated with a caret (^) and an empty line.

Dror Harari
  • 3,076
  • 2
  • 27
  • 25