Page 1 of 1

Finding and replace an string in a text file

Posted: 08 Dec 2011 12:35
by balubeto
HI

I have to create two scripts (to be included in a bat file):

1) A script that finds a specific string in a text file so that it is replaced with another string.

2) A script that finds a specific string in a text file so that its entire line is replaced from another string.

These scripts should work on Windows 7 SP1 32/64 bit. So, how do I do this?

THANKS

BYE

Re: Finding and replace an string in a text file

Posted: 09 Dec 2011 18:52
by orange_batch
Sounds like someone wants us to do their school homework?

Preserve all quotation marks.

1) A script that finds a specific string in a text file so that it is replaced with another string.

Code: Select all

@echo off&setlocal enabledelayedexpansion

set file="my_text.txt"
set out="result.txt"
set "find=What to find."
set "replace=Replace with this."

for /f "usebackq delims=" %%x in (%file%) do (
set "check=%%x"
set "check=!check:%find%=%replace%!"
echo !check!>>%out%
)

2) A script that finds a specific string in a text file so that its entire line is replaced from another string.

Code: Select all

@echo off&setlocal enabledelayedexpansion

set file="my_text.txt"
set out="result.txt"
set "find=What to find."
set "replace=Replace with this."

for /f "usebackq delims=" %%x in (%file%) do (
if "%%x"=="!find!" (
echo !replace!>>%out%
) else (
set "text=%%x"
echo !text!>>%out%
))

Re: Finding and replace an string in a text file

Posted: 10 Dec 2011 01:55
by balubeto
How should I do if the string to find or replace contains the " symbol?

Also, I tried the first script:

Code: Select all

@echo off&setlocal enabledelayedexpansion

set file="D:\Users\Public\Documents\VM_Windows_7_template.vmx"
set out="result.txt"
set find="VM_Windows_7_template"
set replace="VM_Windows_7_template-flat"

for /f "usebackq delims=" %%x in (%file%) do (
set "check=%%x"
set "check=!check:%find%=%replace%!"
echo !check!>>%out%
)


with a file that has as content:

Code: Select all

Memsize = "4096"
scsi0:0.present = "TRUE"
scsi0:0.fileName = "VM_Windows_7_template.vmdk"
floppy0.startConnected = "FALSE"
floppy0.fileName = ""


but it does not work because the output file is the same. Why?

THANKS

BYE

Re: Finding and replace an string in a text file

Posted: 10 Dec 2011 02:46
by orange_batch
Did you try replacing the inner text with a quotation mark? Such as set "find="" or set "replace=""

In the second script, it had a bug but I fixed it.