Search code examples
windowsbatch-filecmdfile-rename

What am I doing wrong in my windows batch script, I'm trying to understand the logic behind script


So here is a bat script that is working, it is removing letter P from every jpg files that start with letter P in a folder.

@echo off
  for %%a in (p*.*) do ren "p*" "/*"

I want to understand the logic behind this script, so I'm messing around with it.

If I want remove letter P at end of files, I changed it but it didn't work,

What exactly am I doing wrong?

All I need to move P from beginning to end in the %%a and after ren command.

@echo off
      for %%a in (*.*P) do ren "*P" "/*"

Solution

  • You mention that you specifically want to rename the file starting with p and have a .jpg extension. Meaning you want to move the starting p to the end of the name, before the extension. This example does exactly that:

    @echo off
    setlocal enabledelayedexpansiob
    Pushd "D:\location of files here"
    for %%i in (p*.jpg) do (
        set "name=%%~ni"
        ren "!name:~1!!name:~0,1!%%~xi"
    )
    Popd
    

    Short explanation. We do for p*.jpg to ensure we only iterate through files starting with p and have a jpg extension.

    We set the variable %name% to the name only of the file %%~ni (also seen as !name! because we have enabled delayedexpansion)

    We then use variable expansion to strip parts of the name. Here we say print everything in the variable !name! excluding the first character as !name:~1!

    Then use only the first character as starting from character zero, selecting only one. !name:~0,1! and simply give it back the extension %%~xi

    To read more on the help of everything we have used here, open cmd and type the following:

    for /?
    set /?
    setlocal /?
    

    Everything we mentioned in this answer, is available in the help of the above.