Roke
Roke

Reputation: 300

Batch Files - How can I replace a word after finding it?

I am using batch to create variables for another program (which I did not make). I need to modify these strings; but not replace the whole file (it is very long). However, when researching the topic, many people just suggest the findstr command (which finds BUT does NOT replace string). Is there any way to replace a string rather than rewrite the whole file?

Example Text:

Oh it's a lovely day

Changes in bold:

oh it's a new day

(Instead of rewriting the whole text, it just effects certain areas.

Upvotes: 2

Views: 61

Answers (2)

CristiFati
CristiFati

Reputation: 41137

You can use batch string substitution; here I assumed that what needs to be replaced is:

  • the whole phrase: Oh it's a lovely day - oh it's a new day

Go through the file line by line and do the replacements. Here's the code:

@echo off
for /f "tokens=*" %%f in (.\a.txt) do (
    call :replace_func %%f
)
goto :eof

:replace_func
    set _local0=%*
    if "%_local0%" equ "" goto :eof
    :echo l0 %_local0%
    echo %_local0:Oh it's a lovely day=oh it's a new day%
    goto :eof

The string substitution happens in replace_func, while the file is being iterated in the for loop.

For the a.txt file contents:

Oh it's a lovely day1

Some other text

Oh it's a lovely day2

Oh it's a lovely day3

lovely day

the output would be:

oh it's a new day1

Some other text

oh it's a new day2

oh it's a new day3

lovely day

@EDIT1: rookie mistake: no "goto :eof" after the loop. The if clause hidden any garbage output generated by this.

Upvotes: 2

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You can replace strings in a batch file using the following command:

set str="Oh it's a lovely day"
set str=%str:O=o%
set str=%str:lovely=new%

And will get in 'str': oh it's a new day

Upvotes: 0

Related Questions