How to rename in bulk following a specific structure in batch?

44 views Asked by At

I'd like to rename in bulk shortcuts only(.lnk) in a folder. Currently, the format of the name I expect the script to rename is as follows:

V[number] - [lastName] [firstName]
  • number: an integer up-to 5 digits
  • lastName & firstName: a string starting with a Capital character.

I want the script to rename to this structure using a RegEx:

[lastName] [firstName] - V[number]

With my script, it renames correctly on the first run, but then renames into unwanted strings.

So far, I've been able to rename with the following:

@echo off
setlocal enabledelayedexpansion

REM Set the log file name
set "log_file=renaming_log.log"

REM Redirect the output to the log file
>>"%log_file%" (
    echo Renaming shortcuts in folder: %cd%
    echo -----------------------------------------------------
)

REM Loop through all .lnk files in the current folder
for %%F in (*.lnk) do (
    set "file=%%~nxF"
    set "employeeID=!file:~1,5!"
    set "name=!file:~8,-4!"
    
    REM Rename the shortcut
    ren "%%F" "!name! - V!employeeID!.lnk"
    
    REM Log the result
    >>"%log_file%" echo Renamed "%%~nxF" to "!name! - V!employeeID!.lnk"
)

REM Display completion message
echo Shortcut renaming completed. Check "%log_file%" for details.
pause

Now, I'd like to add a condition using findstr to only rename according to the structure above. New code in the for loop would look something like this:

for %%F in (*.lnk) do (
    set "file=%%~nxF"
    set "employeeID=!file:~1,5!"
    set "name=!file:~8,-4!"
    
    REM Check if the file name matches the desired structure using findstr
    echo "!file!" | findstr /R /C:"^V[0-9]{1,5} - [A-Z][a-z]* [A-Z][a-z]*$" > nul
    if not errorlevel 1 (
        REM Rename the shortcut
        ren "%%F" "!name! - V!employeeID!.lnk"
        
        REM Log the result
        >>"%log_file%" echo Renamed "%%~nxF" to "!name! - V!employeeID!.lnk"
    ) else (
        REM Log the result for non-matching shortcuts
        >>"%log_file%" echo Skipped "%%~nxF" as it does not match the desired structure.
    )
)

However this always Skips. What am I missing in the findstr command?

Thanks

0

There are 0 answers