How to rename the files in the path with new different names in batch?

拥有回忆 提交于 2020-01-13 08:17:28

问题


I have one file destination.txt with path information about my CDs:

 C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SME99.ISO
C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\Biomasse.iso 
C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SAMPE36.ISO

Now I have to rename the ISOs with the numbers that are in the file PPN.txt one after another:

470692405 
394006801 
348117876 

So it should be

SME99.ISO -> 470692405.ISO
Biomasse.iso -> 394006801.ISO
Sampe36.ISO -> 348117876.ISO

I have the following code for it:

< "PPN.txt"  (for /F "usebackq delims=" %%a in ("destination.txt") do (
  set/P out="" & rename "%%a" "!out!%%~xa" 

I want to modify the code that way that it works for the file destination.txt:

Success on: "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SME99.ISO" 
Error on:   "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\Biomasse.iso" 
Success on: "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SAMPE36.ISO" 

If "Success on" stays before the path in destination.txt the image should be renamed as always only with the number from PPN.txt. But if "Error on" stays before the path in destination.txt the image should be renamed like this e_%number from PPN.txt% . So it should be additional prefix e_ there


回答1:


Edit Batch now takes the prefix into account, splitting the lines from destination.txt at the colon into %%A and %%B

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
< "PPN.txt"  (
    for /F "usebackq tokens=1,* delims=:" %%A in ("destination.txt") do (
        Set "out="
        Set /P "out="
        Set "out=!out: =!"
        If /i "%%A" equ "Success on" (
            ren %%B "!out!.ISO" && echo Renamed %%B to "!out!.ISO" 
        ) Else If /i "%%A" equ "Error on" (
            ren %%B "e_!out!.ISO"  && echo Renamed %%B to "e_!out!.ISO" 
        ) Else (Echo unknown prefix "%%~A")
    ) 
)

Simulated ISO files returned this output:

Renamed  "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SME99.ISO"  to "470692405.ISO"
Renamed    "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\Biomasse.iso"  to "e_394006801.ISO"
Renamed  "C:\Users\NekhayenkoO\Desktop\LOG Dateien CD Imaging\SAMPE36.ISO"  to "348117876.ISO"



回答2:


Try:

< PPN.txt (
  for /F "delims=" %%a in (destination.txt) do (
    set/P out="" & rename "%%a" "!out!%%~xa"&&echo Success on: "%%a"||(
      echo Error on:   "%%a" & rename "%%a" "e_!out!%%~xa"
    )
  )
)

&& will handle sucess of previous operations (errorlevel 0), || will handle failure.



来源:https://stackoverflow.com/questions/45237964/how-to-rename-the-files-in-the-path-with-new-different-names-in-batch

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