Search code examples
batch-filefilenamesfile-renamebatch-rename

Rename files with batch file if filename is missing string


I am trying to write a batch file that renames filenames if the filename does not contain a specific string at the end. For example, I have a folder that contains the following files:

Test File1.csv
Test File2 Zac.csv

For every file that doesn't contain 'Zac' (without quotes) at the end (before the extension), I want to add 'Zac' to the filename. So the result would be:

Test File1 Zac.csv
Test File2 Zac.csv

This is what I currently have for the batch file:

for %%f in (*.csv) do (ren "%%f" ???????????????????????????????" Zac.csv"

But this will add 'Zac' to all files, even if they already contain 'Zac'. How can I change only those files that do not have 'Zac' at the end?

Thank you very much!


Solution

  •     for /f "delims=" %%a in ('dir /b /a-d *.csv ^|findstr /iv "zac"') do echo ren "%%~a" "%%~na Zac%%~xa"
    

    Look at the output and remove echo if it looks good.
    Note: if the file exists already ren fails and you get an error message.