while adding prefix to specif files using batch file it adds prefix two time for first file because of bracket '[]'

StackOverflow https://stackoverflow.com/questions/19441630

  •  01-07-2022
  •  | 
  •  

Frage

i'm trying to add prefix to all files in cur dir and sub dir and i'm succeed in this using following code:

@echo off
pushd "D:\z.Temp\Test\"
for /r %%j in (*) do (
   rename "%%j" "[nilesh.uk.to]-%%~nxj"
)
popd

But When I Try To Add Prefix For Perticular File Types Such As:

@echo off
pushd "D:\z.Temp\Test\"
for /r %%j in (*.html *.js) do (
   rename "%%j" "[nilesh.uk.to]-%%~nxj"
)
popd

the it works but it gives me output such as:

demo1.html  -->  [nilesh.uk.to]-[nilesh.uk.to]-demo1.html
demo2.html  -->  [nilesh.uk.to]-demo2.html
demo3.html  -->  [nilesh.uk.to]-demo3.html

demo1.js  -->  [nilesh.uk.to]-[nilesh.uk.to]-demo1.js
demo2.js  -->  [nilesh.uk.to]-demo2.js
demo3.js  -->  [nilesh.uk.to]-demo3.js

Here Each first file adding prefix two time

And If I Remove [] from nilesh.uk.to then it works perfectly but i want prefix as [nilesh.uk.to] please frendz tell me what to do....

War es hilfreich?

Lösung

The problem is, that the renamed files can be found and renamed a second time.

Add an ECHO rename "%%j" "[nilesh.uk.to]-%%~nxj" to your code and you will see something like

rename "C:\temp\bracket\demo1.txt" "[nilesh.uk.to]-demo1.txt" rename "C:\temp\bracket\demo2.txt" "[nilesh.uk.to]-demo2.txt" rename "C:\temp\bracket\demo3.txt" "[nilesh.uk.to]-demo3.txt" rename "C:\temp\bracket[nilesh.uk.to]-demo1.txt" "[nilesh.uk.to]-[nilesh.uk.to]-demo1.txt"

So you need to force the FOR loop to take each file only once.

You could change it to

for /F "delims=" %%j in ('dir /s /b *.html') do (
....

This works, as the dir /s /b *.html will be completly executed before the first rename command will be executed.

Andere Tipps

I don't know but I will take a guess. I have some reason to believe it's a good guess. Remove the brackets (the ()) brackets and put commands on one line.

If you do that and the script still doesn't work I'll look at it closely.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top