0

I'll confess that I was never all that good at writing DOS Batch scripts beyond basic stuff. I've had need to write a script to read an HTML template file and create a new file from it... Now I can read the file into a variable using:

for /f "delims=" %%x in (template.html) do set fileData=%%x

and I can echo the variable out to see that the html data is in there. But when I try to write it out using:

echo %fileData%>test2.html

I get an error:

The system cannot find the file specified.

I'm not sure if it has anything to do with the variable containing html tags that are confusing the output to file?

0

2 Answers 2

2

Yep, the < and > tag characters are being evaluated literally by echo %fileData%. Use the delayed expansion style to prevent that from happening.. Put setlocal enabledelayedexpansion at the top of your script and echo !fileData!>test2.html.

As a side note, you might benefit from a batch script heredoc for composing your HTML. If you're comfortable with JavaScript and you're feeling adventurous, it's also possible to interact with the DOM by calling Windows Scripting Host methods in a hybrid script.

One other note: If you

for /f "delims=" %%x in (template.html) do set fileData=%%x

your fileData variable gets reset over and over for each line in template.html, until it ultimately ends up containing only the last line. Batch variables can't (easily) contain multiple lines. You need to do your processing within the loop, something like this:

@echo off
setlocal enabledelayedexpansion
(
    for /f "delims=" %%x in (template.html) do (
        set "fileData=%%x"
        echo !fileData:search=replace!
    )
)>test2.html
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks rojo, that almost does it for me... For some reason, I now only get the last line of the file, so the echo of !fileData! returns </html>, so it seems to have discarded all the file contents, except for the last line. Maybe I need a different method for reading in the file to my variable?
Awesome! Thanks for the help! The only thing I had to do was use >>test2.html at the end, though, since >test2.html only wrote the last line of my file.
1

I've struggled with this for the past ~2 hours, just to discover that it can be done in one line:

 type file.html>>otherFile.html

As far as I know, it should work with any file extension (as long as the type command works with it). I'm not sure if this completely suits your needs but it's a pretty neat way to append a file's content to another file. P.S.: Don't judge me if I made a mistake, I'm also a batch script newbie.

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.