4

I have a batch file that I want to open a file and do a very simple search and replace of that file and then save (overwrite) the file it did the search and replace on.

I know how to read the first line of a file:

set /p file= < file.txt

but struggling on the batch method of reading a whole file and doing search/replace on it.

4 Answers 4

6

Replace the filename.txt and search1/replace1 with your filename and the proper search/replace strings or text.

 Echo off
    set "textfile=filename.txt"
    set "tempfile=filenametemp.txt"
    (for /f "delims=" %%i in (%textfile%) do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:search1=replace1!"
        echo(!line!
        endlocal
    ))>"%tempfile%"
    del %textfile%
    rename %tempfile%  %textfile%
Sign up to request clarification or add additional context in comments.

Comments

5

It's hard to give a definitive answer because it's not clear what you mean by very simple search and replace, but here are all the elements needed:

Reading a file

You can read a file line by line using for /f :

for /f %%a in (myfile.txt) do (
    echo %%a
)

Replace text

Here's one way I know how to replace text occurrences:

SETLOCAL ENABLEDELAYEDEXPANSION
for /f "delims=" %%a in (myfile.txt) do (
    SET s=%%a
    SET s=!s:stringtoreplace=replacementstring!
    echo !s!
)

This will output all lines of myfile.txt and replace stringtoreplace with replacementstring .

Overwrite a file

You may consider writing first into a new temporary file, and then replacing the original file with the new temporary one.

With the above examples, it's as simple as adding >>yourtempfilename.txt after the echo statements.

Filter lines of a file

If you simply want to delete some lines from a file, you may also consider the findstr command (help findstr).

2 Comments

As written, the code will not preserve blank lines. That may not be acceptable.
@dbenham How should it be written to preserve blank lines?
2

To add to Johan A's answer, if you want the find/replace strings to be supplied from a user input instead of hardcoded, you can write it like this.

(I also added a finalfilename variable since I wanted to leave the original file untouched and just generate a new file with the output. Just set it the same as the sourcefile name if you want it to overwrite the original)

@ECHO OFF
set "sourcefile=sourcefilename.txt"
set "tempfile=filenametemp.txt"
set "finalfilename=outputfile.txt"

ECHO Enter search term to find:
set /p search1=

ECHO Enter replacement string:
set /p replace1=

ECHO Finding  %search1%  and replacing with  %replace1%

(for /f "delims=" %%i in (%sourcefile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search1%=%replace1%!"
    echo(!line!
    endlocal
))>"%tempfile%"

:: Delete potential existing final file to avoid duplicate error when renaming
del %finalfilename%
ECHO Setting filename to  %finalfilename%
rename %tempfile%  %finalfilename%

ECHO Done
:: Pause to see messages
PAUSE

Comments

1

You can do a search and replace in a file or using a hard coded string or a regular expression using a VBScript (which can be executed by a batch script).

Here is an example of a of a search and replace using a hard coded search criteria:

<job>
<script language="JavaScript">
    var fso = new ActiveXObject("Scripting.FileSystemObject");  
    var MyFile = fso.GetFile("c:\\file.json");
    var txt = MyFile.OpenAsTextStream(1).ReadAll();
    txt = txt.replace("criteria", "replacing value");
    WScript.echo("Replaced File"+txt);
    var out = MyFile.OpenAsTextStream(2);
    out.write(txt);
</script>

Save this script in a file called replace.wsf. You can then execute the script from a batch file like this (in a Windows operating system):

pushd %~dp0
cscript c:\replace.wsf

If you need to do a search and replace based on a regular expression then I suggest looking at this example : regex search replace in batch

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.