Conditional rename inside for statement

2019-07-28 06:03发布

I'm looking for a solution that lets me rename all files, except .bat files, in the folder with a substring, say APPENDTEXT, appended at the end. I've tried this before and it worked out great! Now I'm at a loss on how to further improve it. I want it to recognize files that already have the substring inside the filename and skip renaming just those files.

In all my approaches, I've failed and ended up appending nonce or double the substring.

A scenario would be some folder with mixed files such as:

EXAMPLEFOLDER
|---- file1.txt
|---- file2APPENDTEXT.txt
|---- file3APPENDTEXT.txt
|---- file4.txt

I want the files in this folder to be renamed something like this when I run the batch file:

EXAMPLEFOLDER
|---- file1APPENDTEXT.txt
|---- file2APPENDTEXT.txt
|---- file3APPENDTEXT.txt
|---- file4APPENDTEXT.txt

Currently, they are being renamed like this(or none at all):

EXAMPLEFOLDER
|---- file1APPENDTEXT.txt
|---- file2APPENDTEXTAPPENDTEXT.txt
|---- file3APPENDTEXTAPPENDTEXT.txt
|---- file4APPENDTEXT.txt

Then I'm thinking of improving it further by exploring into all subfolders.

EXAMPLEFOLDER
|---- file1APPENDTEXT.txt
|---- file2APPENDTEXT.txt
|---- file3APPENDTEXT.txt
|---- file4APPENDTEXT.txt
|---- EXAMPLEFOLDER2
|---- |---- file21APPENDTEXT.txt
|---- |---- file22APPENDTEXT.txt

I've not done it yet because I still can't figure out how to stop renaming filenames that already contain the substring APPENDTEXT. It'd be great if the solution is built upon this answer. Can someone help me?

1条回答
手持菜刀,她持情操
2楼-- · 2019-07-28 06:24
@echo off
setlocal EnableDelayedExpansion

set "var=APPENDTEXT"
for /F "delims=" %%a in ('dir *.* /b /a-d ^| findstr /v /i "\.bat$" ') do (
   set "name=%%~Na"
   if "!name:%var%=!" equ "!name!" ren "%%a" "%%~na%var%%%~xa"
)
pause
查看更多
登录 后发表回答