0

I am writing some batch code to simplify a process I have of downloading some files, renaming them, and then copying them to replace the old ones. I'm running into an issue where I have a FOR loop read in a list of files from a directory, then try to modify the filenames.

The filenames all have FLY in the name, and I want to remove all text after FLY. I can't use tokens because the filenames are inconsistent in length, have multiple spaces, and wouldn't have a set number of tokens. I can't use substring because there is not a set number of characters after FLY.

I've tried using the examples at SS64 and also read numerous threads on here but nothing really seems to match my situation.

Here's the code snippet, appreciate if someone can tell me where I'm going wrong:

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "TOKENS=*" %%A IN ('DIR /B ^"%~DP0VFR^"') DO (
    SET FILENAME=%%A
    SET REMOVETEXT=!FILENAME:*FLY=!
    SET NEWFILENAME=!FILENAME:!REMOVETEXT!=!
    ECHO !FILENAME! will be renamed !NEWFILENAME!
)

When I insert echos to see what's going on everything works as expected up until the last SET, where somehow the ending result is !NEWFILENAME! is blank.

2 Answers 2

1

Hmm. My results were different from yours.

The " in your dir do not need to be escaped.

The problem with your set statement is that it's interpreted as

SET NEWFILENAME=!FILENAME:!   +   REMOVETEXT   +   !=!

and since FILENAME: and = are not existing variables, each will be replaced by nothing yielding "REMOVETEXT", not blank as you claim.

The solution is to use a two-stage evaluation of newname

call SET NEWFILENAME=%%FILENAME:!REMOVETEXT!=%%

which is resolved as

SET NEWFILENAME=%FILENAME:current_value_of_REMOVETEXT=%

in a sub-shell.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct, when I took a second look I was getting "REMOVETEXT" as the contents.
0

After cold brew it occurred to me that I might be going about this all wrong and making it more complicated than it needs to be... I decided to try directly renaming the files with wildcards and that actually worked. Didn't even need the FOR loop.

REN "%~DP0VFR\*FLY*" *FLY

No idea why the first (and overly convoluted) solution I tried didn't work, but this does with a lot less code!

1 Comment

A perfect example of Occam's Razor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.