Reputation: 33
I can't wrap my head around the variable substitution mechanism of DOS batch files, especially in for loops.
Simplified batch problem: imagine the following directory
01foo.txt
02foo.dir (this is a directory)
bar01 (this is a directory)
bar02 (this is a directory)
i want to move all files/directories in this directory that do NOT start with 'bar' to a subdirectory that is bar+_the_first_2_characters_of_the_filename_or_directory_name.
In this case, 01foo.txt would be moved into bar01 and 02foo.dir would be moved into bar02.
The following script is my first attempt:
setlocal EnableDelayedExpansion
for %%A in (*) do (
set _x=%%A
if (!_x:~0,2! NEQ "bar") move %%A bar!_x:~0,2!
)
endlocal
apart from the fact that this seems to loop only for files, it simply doesn't work at all :-). I get an error in the if statement saying "3! was unexpected at this time"
Any idea on how to improve the situation/script?
Thanks
Upvotes: 1
Views: 1898
Reputation: 82337
It's only a problem of the syntax...
The IF
statement does not expect not accept surrounding brackets.
The the comma in !_x:~0,2!
breaks the IF-statment, you could quote both parts or move it into an own set prefix=!_x:~0,2!"
line.
If you quote "bar"
you also need to quote "!prefix!"
.
That's all
setlocal EnableDelayedExpansion
for %%A in (*) do (
set "_x=%%A"
set "prefix=!_x:~0,2!"
if "!prefix!" NEQ "bar" move %%A bar!prefix!
)
endlocal
Upvotes: 2