1

I tried searching previous questions but none worked, or I couldn't adapt them to my needs.

I want to write a script that asks for:

  • folder
  • criteria
  • old string
  • new string

And replace every file in the specified folder and subfolders (and force user to type one) with specific criteria (for example, it must be a ".cue" file), and:

  1. If the file is read-only, disable it.
  2. Search for specified old string in the file content and replace it with new string , and save changes in same file.
  3. If the file was read-only, enable it again.

I have this code so far, but I don't know what to do in the do part:

@echo off 

setLocal enableDELAYedexpansion

:START
set "var2="
set /P var2="type folder "

if "%var2%"=="" goto ERROR

set /p old="old string ? "
set /p new="new string ? "
set /p files="what criteria ? "
echo modifying files...

for /r "%var2%" %%v in (%%files) do (

???

)
pause

goto START

:ERROR
echo type something!!
goto START

1 Answer 1

2

Use FOR /F with DIR /B /S /A-D-R to get files that don't have the read only flag set.

Then use any of several published methods to modify a text file. I prefer to use a hybrid JScript/batch utility called REPL.BAT that performs a regex search and replace on stdin and writes the result to stdout. It is pure native script that runs on any modern Windows machine from XP onward - no 3rd party executable required. Full documentation is embedded within the script.

The L option causes a literal search, and the V option gets the search and replace values from variables instead of from string literals.

Assuming REPL.BAT in your current folder, or better yet, somewhere within your path:

@echo off
setlocal

:START
set "var2="
set /P var2="type folder "

if "%var2%"=="" goto ERROR

set /p old="old string ? "
set /p new="new string ? "
set /p files="what criteria ? "

for /f "delims=" %%F in ('dir /b /s /a-d-r "%var2%\%files%" 2^>nul') do (
  echo modifying %%F
  type "%%F" | repl old new lv >"%%F.new"
  move /y "%%F.new" "%%F" >nul
)

pause

exit /b

:ERROR
echo type something!!
goto START
2
  • thanks! but it didn't worked. It gives the error: "file not found" (and I need it for folders). I have REPL.BAT in %var2% folder and same folder as .bat. But don't worry, I have anothother script that worked!
    – Ruben
    Sep 25, 2013 at 19:51
  • @Ruben - It absolutely works in my hands as long as a valid folder and "criteria" is entered, and files are found. I edited the answer to eliminate error messages if the criteria and folder result in no files found.
    – dbenham
    Sep 25, 2013 at 20:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .