copenndthagen
copenndthagen

Reputation: 50732

Batch command to find/replace text inside file

I have a template file (say myTemplate.txt) and I need to make some edits to create my own file (say myFile.txt) from this template.

So the template contains lines like

env.name=
env.prop= 
product.images.dir=/opt/web-content/product-images

Now I want this to be replaced as follows;

env.name=abc
env.prop=xyz
product.images.dir=D:/opt/web-content/product-images

So I am looking for batch commands to do the following;

1. Open the template file.
2. Do a kind of find/replace for the string/text
3. Save the updates as a new file

How do I achieve this ?

Upvotes: 3

Views: 3934

Answers (1)

dbenham
dbenham

Reputation: 130819

The easiest route is to modify your template to look something like this:

env.name=!env.name!
env.prop=!env.prop!
product.images.dir=/opt/web-content/product-images

And then use a FOR loop to read and write the file while delayed expansion is enabled:

@echo off
setlocal enableDelayedExpansion
set "env.name=abc"
set "env.prop=xyz"
(
  for /f "usebackq delims=" %%A in ("template.txt") do echo %%A
) >"myFile.txt"

Note it is much faster to use one over-write redirection > for the entire loop then it is to use append redirection >> within the loop.

The above assumes that no lines in template begin with ;. If they do, then you need to change the FOR EOL option to a character that will never start a line. Perhaps equal - for /f "usebackq eol== delims="

Also the above assumes the template doesn't contain any blank lines that you need preserved. If there are, then you can modify the above as follows (this also eliminates any potential EOL issue)

@echo off
setlocal enableDelayedExpansion
set "env.name=abc"
set "env.prop=xyz"
(
  for /f "delims=" %%A in ('findstr /n "^" "template.txt"') do (
    set "ln=%%A"
    echo(!ln:*:=!
  )
) >"myFile.txt"

There is one last potential complicating isse - you could have problems if the template contains ! and ^ literals. You could either escape the chars in the template, or you could use some additional substitution.

template.txt

Exclamation must be escaped^!
Caret ^^ must be escaped if line also contains exclamation^^^!
Caret ^ should not be escaped if line does not contain exclamation point.
Caret !C! and exclamation !X! could also be preserved using additional substitution.

extract from templateProcessor.bat

setlocal enableDelayedExpansion
...
set "X=^!"
set "C=^"
...

Upvotes: 6

Related Questions