Batch: find file and rename it / find file and del

2019-07-27 11:53发布

So... yes, Im pretty newbie. Still trying to explain as good as possible. But needing help with such thing as finding exact file from C: drive (with batch), and rename it. Also wanted to know how to find file from C: and delete it. (2 problems in 1 thread...)

Problem 1. example: I want to find file called "text1.txt" from C: drive with batch, if successfully found, rename it as "text2.txt".

Problem 2. example: I want to find file called "image1.jpg" from C: drive with batch, if successfully found, delete it.

Or how this could be done with batch? del image1 only checks same folder where it already is, same with rename. How to find these files with batch from whole C: disk? Just example. 2 little things to solve, rename and delete by searching for exact files with batch. How about deleting file from subfolder with batch? But sorry my low know-how, must start these things from somewhere.

2条回答
爷的心禁止访问
2楼-- · 2019-07-27 12:11

Oh, it's great to have some good-loking programmers! Most programmers I know are UGLY.

for /f "delims=" %%i in ('dir /s /b /a-d "text.txt"') do (ren "%%i" text2.txt)

Should do the rename task. You should prepend the drive and starting directory to the filename though, or it will rename ALL the text.txt files in ALL subdirectories. Hence ...dir /s/b "c:\users\kaster\text.txt"... will process "c:\users\kaster\" and all of the directories below and rename ALL of the files named text.txt to the new name.

It works by performing a DIRscan in /b basic mode (ie filenames only) /s including subdirectories /a-d ignoring matching directory names for files named "text.txt" - and the full filename is assigned to %%i. The delims clause makes sure that any spaces are not interpreted as delimiters.

See

`FOR ?` 

from the prompt for documentation.

ANd if you are executing this directly from the prompt, change each %% to %

The second command is substantially easire

del /s "image1.jpg"

Again, prepend the starting path, and be VERY, VERY careful. This will delete ALL filenames matching "image1.jpg" in and under the specified directory.

Throughout, quoting the filenames ensures that spaces in file or directorynames are correctly processed.

查看更多
成全新的幸福
3楼-- · 2019-07-27 12:30

Try this. If the output is OK, remove the echo command from the line.

for /f "delims=" %%i in ('dir /s /b /a-d \file1.txt \image1.jpg') do if "%%~nxi"=="file1.txt" (echo ren "%%~i" "text2.txt") else if "%%~nxi"=="image1.jpg" echo del "%%~i" 
查看更多
登录 后发表回答