1.

Solve : TOUGH!replace text in file where text like hello*?

Answer»

Hello

The mission:

1.search all files in c:\ and its subdir with the NAME text.txt
2.next,find a string inside the file where it is like "greeting=hello"
are replace it with the string "greeting=goodbye".
if the string is "greet=hello" i don't want to change it.
Note the differences between "greeting=hello" and "greet=hello"

Is this possible to do?

here is what I have so far.

------------

setlocal enabledelayedexpansion
set pathToDirs=c:\test
set tmpfile=%TMP%\abc.123.aux
if exist %tmpfile% del %tmpfile%

for /f %%d in ('dir "test.txt" %pathToDirs% /s/b') do (

call :REPLACE_TEXT %%d hello goodbye
)
goto :eof

:REPLACE_TEXT
for /f "delims=" %%x in ('type %1') do (
set tmp=%%x
echo !tmp:%2=%3! >> %tmpfile%
)
move /y %tmpfile% %1 > NUL
never liked to do file manipulations in batch.
Code: [SELECT]##python code
import os,fileinput,sys
found = []
somedir="c:\\somedir
for root,dirname,names in os.walk(somedir): #traverse the directory and subdirectories
for files in names:
if os.path.isfile(files) and files =="test.txt":
found.append(os.path.join(root,files)) #get all test.txt into array
# process all found test.txt in place
for lines in fileinput.input(found,inplace=1):
if "greeting==hello" in lines:
lines = lines.replace("greeting==hello","greeting==goodbye")

The gurus here will come up with a batch one soon...There is a DISCONNECT with what you wrote, your DIR command and the SET statement:

Quote

1.search all files in c:\ and its subdir with the name text.txt

set pathToDirs=c:\test

'dir "test.txt" %pathToDirs% /s/b'

This may work a LITTLE better but Ghostdog is right. Batch code is not a programming language and data manipulation is easier is any of free Windows scripting languages VBScript, JScript, Python, Rexx, etc.

Code: [Select]setlocal enabledelayedexpansion
set pathToDirs=c:
set tmpfile=%TMP%\abc.123.aux
if exist %tmpfile% del %tmpfile%

for /f %%d in ('dir %pathToDirs%\test.txt /a:-d /s /b') do (
call :REPLACE_TEXT %%d hello goodbye
)
goto :eof

:REPLACE_TEXT
for /f "delims=" %%x in (%1) do (
set tmp=%%x
set tmp=!tmp:%2=%3!
echo !tmp! >> %tmpfile%
)
move /y %tmpfile% %1 > NUL

Good luck. 8-)Quote
if the string is "greet=hello" i don't want to change it.


setlocal enabledelayedexpansion
set pathToDirs=c:
set tmpfile=%TMP%\abc.123.aux
if exist %tmpfile% del %tmpfile%

for /f %%d in ('dir %pathToDirs%\test.txt /a:-d /s /b') do (
call :REPLACE_TEXT %%d [highlight]"greeting=hello" "greeting=goodbye"[/highlight]
)
goto :eof

:REPLACE_TEXT
for /f "delims=" %%x in (%1) do (
set tmp=%%x
set tmp=!tmp:%[highlight]~[/highlight]2=%[highlight]~[/highlight]3!
echo !tmp! >> %tmpfile%
)
move /y %tmpfile% %1 > NUL
[/b]

Have fun


Discussion

No Comment Found