Oleg_08
Oleg_08

Reputation: 487

How to search for the certain filename in all subfolders within for loop

I have the following script that renames files in the directory according to the list in file opac_one-hit.log

@ECHO OFF
    SETLOCAL enabledelayedexpansion
    FOR /F "tokens=1,3 delims=;" %%G IN ( opac_one-hit.log) DO (
    ren %%G %%H
    )
    pause

In order to start my script should be located in the same directory where opac_one-hit.log is located. How to build search function in my for loop in order to find the opac_one-hit.log in subfolders and not to copy the script to that subfolder every time.

Upvotes: 0

Views: 61

Answers (2)

Stephan
Stephan

Reputation: 56238

You can get the folder(s) where the file is with:

for /f %%A in ('dir /s /b "c:\basedir\opac_one-hit.log"') do echo %%~dpA

where basedir is the location to start the recursive search (to avoid searching the whole disk).

If you are sure, there is just one of your files, set a variable instead of echoing it or use the below version. Also use the below, to process every found opac_one-hit.log:

@ECHO OFF
SETLOCAL 
for /f "delims=" %%A in ('dir /s /b "c:\basedir\opac_one-hit.log"') do  (
  FOR /F "usebackq tokens=1,3 delims=;" %%G IN ("%%A") DO (
    echo ren "%%G" "%%H"
  )
)
pause

REM remove the echo, when the rename commands are correct.

Upvotes: 1

npocmaka
npocmaka

Reputation: 57322

Not tested:

@ECHO OFF
    SETLOCAL enabledelayedexpansion
    for /r %%# in ("opac_one-hit*.log") do (
      FOR /F "usebackq tokens=1,3 delims=;" %%G IN ( "%%~f#" ) DO (
        ren %%G %%H
      )
    )
    pause

Upvotes: 1

Related Questions