yuehan96
yuehan96

Reputation: 1

How can I pull a substring from a filename with a batch script?

I have hundreds of files I want to rename to match a new convention. Current convention is AA.BBBB.XXX I want to change it to BBBB.AA.XXX

I've cd'd into the folder which holds all of these files. I thought I could simply loop through the files and grab the substrings needed to reconstruct the file name. The problem is that %name% appears to be empty when echoed.

for %%f in (*) do (
    set name=%%f
    set arr=%name:~0,3%
    set sta=%name:~3,5%
    set rest=%name:~8,26%
    set new=%sta%%arr%%rest%
    echo f: %%f
    echo name: %name%
    echo arr: %arr%
    echo sta: %sta%
    echo rest: %rest%
    echo new: %new%
    set
    pause
)

As you can see at the bottom I called 'set' so I can see what's going on with these variables. It shows %name% to be equal to what I expect, yet it shows empty when echoed and my other variable assignments are unable to pull substrings from %name%.

Upvotes: 0

Views: 823

Answers (3)

user6811411
user6811411

Reputation:

In case the dots in your convention are meant to be literal,
you can use them to split the Names with a for /f and reorder the parts.

Edit: due to Compos hint changed the iterating for to check convention with a RegEx

:: Q:\Test\2019\05\23\SO_56266054.cmd
@Echo off
PushD "A:\Test"

For /f "delims=" %%F in ('Dir /B "??.????.*"^|findstr "^..\.....\.*"'
  ) do For /F "tokens=1,2*delims=." %%A in ("%%F"
    ) Do Echo Ren "%%F" "%%B.%%A.%%C"

PopD

If the output looks OK, remove the echo.

Sample output:

> Q:\Test\2019\05\23\SO_56266054.cmd
Ren "AA.BBBB.XXX" "BBBB.AA.XXX"
Ren "CC.DDDD.YYYY" "DDDD.CC.YYYY"
Ren "EE.FFFF.ZZZZZ" "FFFF.EE.ZZZZZ"

Upvotes: 1

abelenky
abelenky

Reputation: 64730

Your approach is fine, if a little bit clumsy.

But I think you need delayed expansion, and using ! instead of %

setlocal enabledelayedexpansion
for %%f in (*) do (
    set name=%%f
    set arr=!name:~0,3!
    set sta=!name:~3,5!
    set rest=!name:~8,26!
    set new=!sta!!arr!!rest!
    echo f: %%f
    echo name: !name!
    echo arr: !arr!
    echo sta: !sta!
    echo rest: !rest!
    echo new: !new!
    set
    pause
)

Upvotes: 0

Compo
Compo

Reputation: 38719

Here's one idea, using delayed expansion:

@Echo Off
For /F Delims^=^ EOL^= %%A In ('Where ".:??.????.???" 2^>NUL') Do (
    Set "_=%%~nA"
    SetLocal EnableDelayedExpansion
    Ren "%%A" "!_:~-4!.!_:~,2!%%~xA"
    EndLocal
)

Upvotes: 0

Related Questions