Search code examples
windowsbatch-filerenamewindows-7-x64batch-rename

Batch script remove everything after a dynamic text from the string/filename


I have a string containing filename like below batch script lines:

set "file1=name.php_2017_23_08_12_22_07"
set "file2=name.vbs_2016_16_12_12_13_03"
....

Now as you see above, the list of filenames and their extensions is variety and I need to get the real filenames with their actual extensions (.php, .vbs) respectively. So when I pass in a function with filename with extension I should get actual filenames like below:

call :restoreFile %file2% ".vbs"

should give me output, removing everything after .vbs in the variable %file2%:

name.vbs

And so on for other variables too.

How can set a function like that, which strips a dynamic substring from filename string ?

I tried the below code, but that doesn't work with dynamic substring or text, which can be substitued from variable:

set targetfile=%file2:.vbs=&rem.%

Solution

  • No need to specify the extension - it's still in the name.

    Use a for /f to split at the first underscore.

    :restoreFile
    Set "FileName="
    For /f "tokens=1* delims=_" %%N in ("%~1") Do Set "FileName=%%N"
    If defined FileName Echo Ren %1 %FileName%
    Goto :Eof
    

    You may even put the date_time in front of the extension and so avoid possible dupes:

    :restoreFile
    Set "FileName="
    For /f "tokens=1* delims=_" %%N in ("%~1") Do Set "FileName=%%~nN_%%M%%~xN"
    If defined FileName Echo Ren %1 %FileName%
    Goto :Eof
    

    The ren commands are prepended with an echo, if the output looks OK remove the echo.