Frage

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!

War es hilfreich?

Lösung

    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.

Andere Tipps

This should work:

@echo off
: create variable to track number of files renamed
set filesRenamed=0
: loop through csv files and call Rename routine
for %%f in (*.csv) do call :Rename "%%f" filesRenamed
: output results
echo %filesRenamed% files renamed
: clear variables
set filesRenamed=
set tmpVar=
: Goto end of file so we don't call rename an extra time
goto :eof

:Rename
: need a local environment variable with filename for manipulation
set tmpVar=%1
: remove the closing quotes
set tmpVar=%tmpVar:~0,-1%
: compare the last 8 characters and rename as necessary
if /I NOT "%tmpVar:~-8%" EQU " Zac.csv" (
    : use original file name parameter which is already quoted
    ren %1 ???????????????????????????????" Zac.csv"
    : increment the renamed file count
    set /A %2=%2+1
)

See this other post for a good description of substring handling in batch files.

using renamer, these input files:

Test File1 Zac.csv
Test File2.csv
Test File3.csv
Test File4.xls
Test File5 Zac.csv

with this command:

$ renamer --regex --find '(Test File\d)(\.\w+)' --replace '$1 Zac$2'  *

results in these new filenames:

Test File1 Zac.csv
Test File2 Zac.csv
Test File3 Zac.csv
Test File4 Zac.xls
Test File5 Zac.csv

let me know if you need any more help.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top