Search code examples
batch-filerenamebatch-processingbatch-rename

Renaming files if they contain 2 strings with batch


I have a file "codes.txt" containing one code per line.

I am trying to search and rename in a folder all files containing a code in their name, and also another string :

@echo off

for /F "tokens=*" %%b in (codes.txt) do  (

// If file names in folder contain %%b and "foo", rename to %%b.'string'
// If file names in folder contain %%b and "foo2", rename %%b.'string2'

)

Thank you


Solution

  • Assuming the file `codes contains:

    1234
    5678
    

    and your dir has a files called:

    foo1234.txt
    1234ABCfoo.txt
    5678.txt
    

    Then this script will do:

    @echo off
    for /f %%i in (codes.txt) do (
       for /f %%a in ('dir /b /a-d *%%i* ^| findstr "foo"') do echo %%a
    )
    

    First it loops through codes.txt, using newlines as delimeters. Then it will do a dir on files containing the codes, and a findstr for foo anywhere in the name. Using the above files it will then echo the only 2 matches found:

    foo1234.txt
    1234ABCfoo.txt
    

    It will not match 5678.txt because it did not have foo anywhere in the name.

    Obviously you would need to change the echo part in my script to the command you want to achieve.