dchin
dchin

Reputation: 311

Read and Write HTML file in Batch Script

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?

Upvotes: 0

Views: 5569

Answers (2)

G.Baldjiev
G.Baldjiev

Reputation: 103

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.

Upvotes: 1

rojo
rojo

Reputation: 24476

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

Upvotes: 2

Related Questions