Search code examples
batch-filerenamefindstr

Batch: find files with specific content and extend existing name


I have about 100 .xml files, but its filenames are not self-explanatory. Therefore I would like to look for a specific word and extend the respecting file with this word. Thanks to some other helpful entries, I could partially figure out how to do this, but somehow the files are not renamed.

Has anybody an idea what is wrong with my code? Thank you in advance.

 chcp 1252  
 SET sourcedir=P:\path  
 FOR /f "tokens=1 delims=." %%a IN ('findstr /c:"3256" "%sourcedir%\*.xml"') DO (  
 ECHO (REN "%%a.xml" "%%a_3256.xml")  
 )  
 pause

Solution

  • chcp 1252  
    SET "sourcedir=P:\path"
    FOR /f "delims=" %%a IN ('findstr /m /c:"3256" "%sourcedir%\*.xml"') DO (  
        ECHO REN "%%a" "%%~na_3256%%~xa"
    )  
    pause
    

    In your code you are using %%a for both arguments to ren command, but the second argument must only contain the name and extension, without path. You can solve it using %%~na, that is, the file name (without path or extension) of the file being referenced by %%a (%%~xa is the extension)

    Also, if the string is found more than once in any file, your code will try to rename the file twice (or more). It is better to use the /m switch in findstr to only retrieve the list of files.

    Rename operations are only echoed to console. If the output is right, remove the echo command.