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

北慕城南 提交于 2019-12-11 04:59:42

问题


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.


回答1:


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.




回答2:


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" 


来源:https://stackoverflow.com/questions/15689510/batch-find-file-and-rename-it-find-file-and-delete-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!