Search code examples
batch-filebatch-rename

files with extra suffix in batch


I'm trying to list all the files which have extra suffix after the extension E.g: .txt.1 or .txt.2 etc..

I'm using txt. but it's giving all the file names instead of only the files with extra suffix

for %%A in (*txt.*) do (call :renum "%%A")

after this I'm writing my program to rename the files accordingly. Can someone please check and help.


Solution

  • One solution would be to filter by extension inside the loop:

    FOR %%A IN (*txt.*) DO (
        IF NOT "%%~xA"==".txt" CALL :renum "%%A"
    )
    

    This works by using the "enhanced substitution of FOR variable references", in this case %%~xA. You can get an overview of all the available substitutions by executing FOR /?.

    Update:

    • This solution does not work case-insensitively, because that was neither explicitly demanded or prohibited. Use IF /I instead of plain IF if case-insensivity is desired.
    • As dbenham notes, there are edge cases:
      • name.txt.txt will not be processed. If that's OK is not clearly stated, but rather likely.
      • name_txt.ext will be processed, which is due to the given wildcard *txt.* and can be avoided by using *.txt.* instead. My rationale to not change it in the first place was that only the OP knows his actual set of files, and I assumed he had a reason for choosing it (a situation common in these types of questions).