Search code examples
windowsfilebatch-filefile-rename

Remove start of filename up to "_"


So im a complete noob at batch programming, but I have this small program which will move files to specific folders based on filename:

@echo off
for %%a in (*.jpg) do (
echo processing "%%a"
  for /f "tokens=1 delims=_" %%b in ("%%~nxa") do (
     move "%%a" "%%b" >nul
  )
)
pause

I want to extend this program to rename some files. The files that the program is moving are all named like: "0_107" or "151_107". which are moved to folders called "0" and "151" respectively.

Now I also want it to chop off everything before and including the underscore. This means that "151_107" should still be moved to folder "151" but the file should be named "107".

Hope this makes sense - thanks in advance

Best Regards


Solution

  • You need to move the FOR-parameter into a variable, then you can remove the leading part with the *<text>= syntax.

    setlocal EnableDelayedExpansion
    for %%a in (*.jpg) do (
        echo processing "%%a"
        for /f "tokens=1 delims=_" %%b in ("%%~nxa") do (
            set "name=%%~a"
            set "name=!name:*_=!"
            echo New destination %%b\!name!
            move "%%~a" "%%b\!name!" >nul
        )
    )