how to replace names recursively via windows batch operation - windows

I want to process a batch operation in a big directory. Actually I have the batch script for that process. But here , I have a problem. Some of the directory names, files names contain " " (space character). So in the batch operation this names passed as 2 arguments . and those lines will not work. So Iwant to rename " " with "_" to overcome this problem .
Example:
process /MyDirectory/Ola and Me/Private/TopSecretPictures/
this gives error. the below one works fine
process /MyDirectory/Ola and Me/Private/TopSecretPictures
My aim is: convert | Ola and Me |>> |Ola_And_Me recursively
:)
thanks in advance ..

The following script renames all files and directories recursively, starting at a given directory, converting spaces to underscores.
spaces_to_underscores.bat source:
#echo off
setlocal
for /r "%~1" %%t in (.) do (
for /f "usebackq tokens=*" %%f in (`dir /b/a-d "%%~t" 2^>nul:`) do (
call :proc "%%~f" "%%~t"
)
for /f "usebackq tokens=*" %%d in (`dir /b/ad "%%~t" 2^>nul:`) do (
call :proc "%%~d" "%%~t"
)
)
exit /b 0
:proc
set fn=%~1
if "%fn: =_%"=="%fn%" exit /b 0
set fn=%~2\%fn: =_%
move "%~2\%~1" "%fn%" >nul:
exit /b 0
Usage:
spaces_to_underscores "My Directory"
Given this directory structure
My Directory
Ola and Me
Private
TopSecretPictures
it will rename the folder "Ola and Me" to "Ola_and_Me", and also rename any files such as "Photo 001.jpg" to "Photo_001.jpg". The starting directory "My Directory" will not be renamed.
WARNING: Do not run this script on standard windows directories, such as "C:\Documents and Settings" or "C:\Program Files" or "My Documents" or "Application Data". There is no "undo" functionality here. Make sure you have a backup.

You can do this in a batch file if you use a feature called "delayed exapansion" that isn't on by default. To switch it on, you need to start cmd.exe with the /v switch:
cmd.exe /v
Once this is on, the following batch script will replace all spaces in %%i with underscores, and spit the result out:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=!S: =_!
echo !T!
)
***Vauge description...***Excluding the for loop itself, the interesting parts of this are:
String substitution using the %var:str1=str2% syntax
Delayed expansion using !var! instead of %var%
First: delayed expansion... without this, the command interpreter (for whatever reason Microsoft decided to code it as) will evaluate all the parameters first, and then run the script: so this version of the script does NOT work:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=%S: =_%
echo %T%
)
With this version the variable 'T' is set to the last value of the for loop before the contents of the (...) block actually execute. Which makes no sense to me. So with delayed execution enabled, we can use the delayed execution variable marks, i.e., !var! rather than %var%. Which gives us the right result.
The other clever bit then is the set T=!S: =_! (which basically says set T to S, replacing every '' ' in S with '_'). Without delayed expansion, this would be written set T=%S: =_%.

Related

How to rename multiple images with an incrementing integer?

Let's say I have a couple of images and I need to rename them and on every iteration add an incremented number.
For this situation I have three images no matter how they name is and I want to rename them like this.
1239.jpg => file1.jpg
file.jpg => file2.jpg
image.jpg => file3.jpg
My commands executed in a command prompt window for this task are:
setlocal EnableDelayedExpansion
set filename=file
set counter=1
for /f "usebackq delims=*" %i in ('dir /b *.jpg') do (set /a counter+=1 ren "%i" "%filename%!counter!.jpg")
But this results in the error message Missing operator.
Can anyone help me with this?
The commands SETLOCAL and ENDLOCAL can be used only in a batch file. Please read this answer for details about the commands SETLOCAL and ENDLOCAL. These two commands do nothing on being executed in a command prompt window. It is necessary to start cmd.exe with option /V:ON to use delayed expansion in a command prompt window as explained by the help output on running cmd /? in a command prompt window.
The usage of usebackq requires enclosing the command line to be executed in ` instead of ' as usual. usebackq is mainly used for processing the lines of a text file of which name is specified in the round brackets enclosed in ".
The following command line with the two commands SET and REN is not of valid syntax. The command SET interprets everything after /a as arithmetic expression to evaluate. In this case the expression misses an operator between 1 and ren whereby ren would be interpreted here as name of an environment variable and not as command to execute next after set.
(set /a counter+=1 ren "%i" "%filename%!counter!.jpg")
The valid command line would be:
set /A "counter+=1" & ren "%i" "%filename%!counter!.jpg"
Enclosing the arithmetic expression in double quotes makes it clear for command SET where the arithmetic expression starts and where it ends. The conditional execution operator & is interpreted by Windows command processor before executing the command SET and results in execution of command REN after command SET even on SET would fail to evaluate the arithmetic expression.
A file renaming task done with Windows command processor is no easy to achieve if
the file extension of the files should not change and
files with any name including those with one or more &()[]{}^=;!'+,`~ should be supported and
there can be already files in the directory with one of the new file names.
For testing the batch file below I created first in a directory following files:
file.jpg
file1.jpg
file2.jpg
file3.jpg
file 4.jpg
File8.jpg
hello!.jpg
image.jpg
The directory was on a FAT32 drive. The file systems FAT16, FAT32 and exFAT return a list of matching directory entries not sorted by name as NTFS which means the list output by command DIR in the main FOR loop in code below is in an unsorted and therefore unpredictable order.
It would be of course possible to append the DIR option /ON to get the list of file names ordered by DIR according to name, but in fact that is not real help in this case, especially because of DIR makes a strict alphabetical sort and not an alphanumeric sort.
A strict alphabetic sort returns a list of ten file names as file1.jpg, file10.jpg, file2.jpg, file3.jpg, ..., file9.jpg while an alphanumeric sort returns a list of ten file names as file1.jpg, file2.jpg, file3.jpg, ..., file9.jpg, file10.jpg.
So here is the commented batch file for this file rename task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=file"
rem The user can run this batch file with a folder path in which all *.jpg
rem files should be renamed with an incremented number. Otherwise the
rem directory of the batch file is search for *.jpg files to rename.
if not "%~1" == "" (
pushd "%~1" || exit /B
) else (
pushd "%~dp0" || exit /B
)
set "FileCount=0"
set "DelayedLoopCount=0"
set "DelayedRenameCount=0"
rem Remove all existing environment variables in local environment of which
rem name starts with DelayedRename_ whereby the underscore is very important
rem because there is also the environment variable DelayedRenameCount.
for /F "delims==" %%I in ('set DelayedRename_ 2^>nul') do set "%%I="
rem Get a captured list of all *.jpg files in current directory and then
rem rename one file after the other if that is possible on no other file
rem has by chance already the new file name for the current file.
for /F "eol=| delims=" %%I in ('dir *.jpg /A-D /B 2^>nul') do call :RenameFile "%%I"
goto DelayedRenameLoop
:RenameFile
set /A FileCount+=1
set "NewName=%FileName%%FileCount%%~x1"
rem Has the file case-sensitive already the right name?
if %1 == "%NewName%" goto :EOF
rem Is the new file name the same as the current name
rem with exception of the case of one or more letters?
if /I %1 == "%NewName%" (
echo Rename %1 to "%NewName%"
ren %1 "%NewName%"
goto :EOF
)
rem Is there no other file which has already the new name?
if not exist "%NewName%" (
echo Rename %1 to "%NewName%"
ren %1 "%NewName%"
goto :EOF
)
rem Another file or folder has already the new name. Remember the name
rem of this file and the new file name with an environment variable for
rem a delayed rename after all other files have been renamed as far as
rem possible.
set /A DelayedRenameCount+=1
set "DelayedRename_%DelayedRenameCount%=|%~1|%NewName%"
goto :EOF
rem It could happen that "file15.jpg" should be renamed to "file3.jpg"
rem while "file3.jpg" exists already which should be renamed to "file12.jpg"
rem while "file12.jpg" exists already which should be renamed to "file20.jpg".
rem This extra loop is used for such worst case scenarios which is executed
rem in a loop until all files have been renamed with a maximum of 50 loop
rem runs in case of one file cannot be renamed and therefore blocking
rem renaming of another file. An endless running loop should be avoided.
rem A file cannot be renamed if a folder has by chance the new file name.
rem A file cannot be renamed if an application has opened the file with
rem a sharing access mode preventing the rename of the file as long as
rem being opened by this application.
:DelayedRenameLoop
if %DelayedRenameCount% == 0 goto EndBatch
for /F "tokens=1-3 delims=|" %%I in ('set DelayedRename_ 2^>nul') do if not exist "%%K" (
echo Rename "%%J" to "%%K"
ren "%%J" "%%K"
set "%%I"
set /A DelayedRenameCount-=1
)
set /A DelayedLoopCount+=1
if not %DelayedLoopCount% == 50 goto DelayedRenameLoop
:EndBatch
popd
endlocal
This batch file output on execution:
Rename "file3.jpg" to "file4.jpg"
Rename "file 4.jpg" to "file5.jpg"
Rename "File8.jpg" to "file6.jpg"
Rename "hello!.jpg" to "file7.jpg"
Rename "image.jpg" to "file8.jpg"
Rename "file2.jpg" to "file3.jpg"
Rename "file1.jpg" to "file2.jpg"
Rename "file.jpg" to "file1.jpg"
The files in the directory were finally:
file1.jpg
file2.jpg
file3.jpg
file4.jpg
file5.jpg
file6.jpg
file7.jpg
File8.jpg
What about the last file?
It has the file name File8.jpg instead of file8.jpg although executed was ren "image.jpg" "file8.jpg". Well, FAT32 is a bit problematic regarding to updates of the file allocation table on a table entry changes only in case of one or more letters.
The solution is using this batch file with two extra FOR loops with # as loop variable and optimized by removing the comments.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=file"
if not "%~1" == "" (pushd "%~1" || exit /B) else (pushd "%~dp0" || exit /B)
set "FileCount=0"
set "DelayedLoopCount=0"
set "DelayedRenameCount=0"
for /F "delims==" %%I in ('set DelayedRename_ 2^>nul') do set "%%I="
for /F "eol=| delims=" %%I in ('dir *.jpg /A-D /B 2^>nul') do call :RenameFile "%%I"
goto DelayedRenameLoop
:RenameFile
set /A FileCount+=1
set "NewName=%FileName%%FileCount%%~x1"
if %1 == "%NewName%" goto :EOF
if /I %1 == "%NewName%" (
echo Rename %1 to "%NewName%"
ren %1 "%NewName%"
goto :EOF
)
if not exist "%NewName%" (
echo Rename %1 to "%NewName%"
ren %1 "%NewName%"
for %%# in ("%NewName%") do if not "%%~nx#" == "%NewName%" ren "%%~nx#" "%NewName%"
goto :EOF
)
set /A DelayedRenameCount+=1
set "DelayedRename_%DelayedRenameCount%=|%~1|%NewName%"
goto :EOF
:DelayedRenameLoop
if %DelayedRenameCount% == 0 goto EndBatch
for /F "tokens=1-3 delims=|" %%I in ('set DelayedRename_ 2^>nul') do if not exist "%%K" (
echo Rename "%%J" to "%%K"
ren "%%J" "%%K"
for %%# in ("%%K") do if not "%%~nx#" == "%%K" ren "%%~nx#" "%%K"
set "%%I"
set /A DelayedRenameCount-=1
)
set /A DelayedLoopCount+=1
if not %DelayedLoopCount% == 50 goto DelayedRenameLoop
:EndBatch
popd
endlocal
The result of this enhanced batch file is even on FAT32:
file1.jpg
file2.jpg
file3.jpg
file4.jpg
file5.jpg
file6.jpg
file7.jpg
file8.jpg
The reason for using | as string separator on execution of
set "DelayedRename_%DelayedRenameCount%=|%~1|%NewName%"
resulting, for example, in execution of
set "DelayedRename_1=|file.jpg|file1.jpg"
set "DelayedRename_2=|file1.jpg|file2.jpg"
set "DelayedRename_3=|file2.jpg|file3.jpg"
is that the vertical bar is not allowed in a file folder name. So it is a very good character to separate the name of the environment variable with the equal sign appended from current file name and from new file name. This makes it possible to use later delims=| for renaming the file and deleting the environment variable.
See also the Microsoft documentations:
Naming Files, Paths, and Namespaces
Using command redirection operators
The equal sign is allowed in a file name. It is even possible that a *.jpg file has as file name =My Favorite Picute=.jpg which is another reason for using | to get executed for example
set "DelayedRename_4=|=My Favorite Picute=.jpg|file9.jpg"
which later results in assigned DelayedRename_4= to loop variable I, =My Favorite Picute=.jpg to loop variable J and file9.jpg to loop variable K in the FOR loop doing the delayed file renames.
Note: Each FOR loop with '...' in the round brackets results
in starting in background one more command process with %ComSpec% /c '...' and
capturing the output written to handle STDOUT like the output of the cmd.exe internal commands DIR and SET
while cmd.exe processing the batch file waits until started cmd.exe terminated (closed) itself after execution of the command line
and then processing the captured lines one after the other by FOR with ignoring empty lines and lines starting with the defined end of line character after doing the string delimiting which is the reason why eol=| is used on main FOR loop as a file name can start with default end of line character ; and which of course should not be ignored here.
The redirection operator > must be escaped with caret character ^ on those FOR command lines to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir or set command line in the separate command process started in background.
The batch file does not use delayed expansion as this would cause troubles on a file name having one or more exclamation marks which would be interpreted as beginning/end of a delayed expanded environment variable reference on command lines like ren "%%J" "%%K". Therefore a subroutine is used for the main file rename loop on which it is necessary to access the two incremented counter values.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
dir /?
echo /?
endlocal /?
exit /?
goto /?
if /?
popd /?
pushd /?
rem /?
ren /?
set /?
setlocal /?
I suggest further to look on:
Microsoft documentation for the Windows Commands
SS64.com - A-Z index of Windows CMD commands
Where does GOTO :EOF return to?
Single line with multiple commands using Windows batch file
Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?

How do I create folder from file name and move files into folder?

I need a windows batch file to create a folder based on part of a file name (the part before an underscore) and move any files that start with the folder name into the folder.
I'm not familiar with windows batch files. I've googled and tinkered a solution which works except that I cannot substring the file name at the underscore.
(Yes there are a few similar threads but nothing I could use to exactly answer my question)
FWIW my unsuccessful solution:
#ECHO OFF
setlocal enabledelayedexpansion
SETLOCAL
SET "sourcedir=C:\Development\test"
PUSHD %sourcedir%
FOR /f "tokens=1*" %%a IN (
'dir /b /a-d "TTT*_*.*"'
) DO (
ECHO MD NEED FILE NAME BEFORE UNDERSCORE HERE
ECHO MOVE "%%a" .\NEED FILE NAME BEFORE UNDERSCORE HERE\
)
(Ideally I'd remove the leading 'TTT' from files too but if necessary can create the files without this.)
Try this batch file code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:\Development\test"
set "DestDir=C:\Development\test"
for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%\TTT*_*" 2^>nul') do (
for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do (
md "%DestDir%\%%B" 2>nul
move /Y "%SourceDir%\%%A" "%DestDir%\%%B\"
)
)
endlocal
The first FOR executes in a separate command process started with cmd.exe /C in background the command line:
dir /B /A-D-H "C:\Development\test\TTT*_*" 2>nul
DIR searches in specified directory for
just non-hidden files because of /A-D-H (attribute not directory and not hidden)
matching the wildcard pattern TTT*_* which could be also just *_*
and outputs to handle STDOUT in bare format because of /B just the file names with file extension, but without file path.
The error message output by DIR to handle STDERR if the specified directory does not exist at all or there is no file matching the pattern is suppressed by redirecting it with 2>nul to device NUL.
Read also the Microsoft documentation about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR captures everything written to STDOUT of started command process and processes the captured output line by line.
FOR ignores by default all empty lines (do not occur here) and all lines starting with a semicolon. A file name could begin with a semicolon. For that reason option eol=| is used to redefine end of line character to vertical bar which a file name can't contain, see Microsoft documentation Naming Files, Paths, and Namespaces. In this case on using TTT*_* as wildcard pattern it is not possible that a file name starts with a semicolon, but it would be possible on usage of *_* as wildcard pattern.
FOR would split up also each line into substrings (tokens) using space/tab as delimiters and would assign just the first space/tab separated string to specified loop variable A. This splitting behavior is not wanted here as file names can contain one or more space characters. Therefore the option delims= is used to define an empty list of delimiters which disables line splitting completely and results in assigning entire file name with extension to loop variable A.
The inner FOR processes just the file name (without extension) as string. This time the file name is split up using the underscore as delimiter because of delims=_ with assigning just first underscore delimited string to loop variable B because of tokens=1. Well, tokens=1 is the default on using for /F and so this option string could be removed from code.
So the outer FOR assigns to A for example TTTxy_test & example!.txt and the inner FOR processes TTTxy_test & example! and assigns to B the string TTTxy.
The command MD creates in set destination directory a subdirectory for example with name TTTxy. An error message is output also on directory already existing. This error message is suppressed by redirecting it to device NUL.
Then the file is moved from source to perhaps just created subdirectory in destination directory with overwriting an existing file with same name in target directory of the file.
The inner FOR loop could be optimized away when there are never files starting with an underscore or which have more than one underscore after first part of file name up to first underscore.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:\Development\test"
set "DestDir=C:\Development\test"
for /F "eol=| tokens=1* delims=_" %%A in ('dir /B /A-D-H "%SourceDir%\TTT*_*" 2^>nul') do (
md "%DestDir%\%%A" 2>nul
move /Y "%SourceDir%\%%A_%%B" "%DestDir%\%%A\"
)
endlocal
Option tokens=1* results in assigning first underscore delimited part of file name to loop variable A and rest of file name to next loop variable B according to ASCII table without further splitting up on underscores.
But please take into account that the optimized version does not work for file names like
_TTTxy_test & example!.txt ... underscore at beginning (ignored by pattern), or
TTTxy__test & example!.txt ... more than one underscore after first part.
The optimized version can be further optimized to a single command line:
#for /F "eol=| tokens=1* delims=_" %%A in ('dir /B /A-D-H "C:\Development\test\TTT*_*" 2^>nul') do #md "C:\Development\test\%%A" 2>nul & move /Y "C:\Development\test\%%A_%%B" "C:\Development\test\%%A\"
Well, the not optimized version could be also written as even longer single command line:
#for /F "eol=| delims=" %%A in ('dir /B /A-D-H "C:\Development\test\TTT*_*" 2^>nul') do #for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do #md "C:\Development\test\%%B" 2>nul & move /Y "C:\Development\test\%%A" "C:\Development\test\%%B\"
See also Single line with multiple commands using Windows batch file for an explanation of operator &.
For additionally removing TTT from file name on moving the file the first batch code is modified with using two additional commands SET and CALL:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceDir=C:\Development\test"
set "DestDir=C:\Development\test"
for /F "eol=| delims=" %%A in ('dir /B /A-D-H "%SourceDir%\TTT*_*" 2^>nul') do (
for /F "eol=| tokens=1 delims=_" %%B in ("%%~nA") do (
md "%DestDir%\%%B" 2>nul
set "FileName=%%A"
call move /Y "%SourceDir%\%%A" "%DestDir%\%%B\%%FileName:~3%%"
)
)
endlocal
The file name is assigned to an environment variable FileName. The value of this environment variable cannot be referenced with just using %FileName% because of all references of environment variable values using percent signs are substituted by Windows command processor in entire command block starting with first ( and ending with matching ) before FOR is executed at all. Delayed expansion is usually used in such cases, but that would result here in file names containing one or more exclamation marks would not be corrected processed by the batch file.
The solution is using %% on both sides of FileName environment variable reference instead of % and force a double parsing of the command line by using command CALL.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
dir /?
echo /?
endlocal /?
for /?
md /?
move /?
set /?
setlocal /?
It is really very simple:
#echo off
for /f "tokens=1-2 delims=_" %%i in ('dir /b /a-d "TTT*_*"') do (
if not exist "%%i" mkdir "%%i"
move "%%i_%%j" "%%i\%%j"
)
We split by _ into 2 tokens, %%i everything before _ and %%j everything after.
We simply create folder (if it does not exist) then move the file with only the name after the _ into the new folder.
So as an example file TTT123_File1.txt will create a folder called TTT123 and place the file into it but rename it as File1.txt
You might consider using Tcl/Tk. Tcl/Tk is an open source script language. You can call it as a stand-alone or execute it from a windows batch file. You will need to install it first if you don't have it yet.
The following Tcl script does what you want:
cd "C:/Development/test"
# glob is a tcl command to list all functions that match the requirements
set files [glob TTT*_*]
foreach f $files {
# use the underscore as a separator to split f and store the parts in dir and fnew
lassign [split $f "_"] dir fnew
if {![file exist $dir]} {
file mkdir $dir
}
file rename $f [file join $dir $fnew]
}
In my opinion, this is a very readable script, even if you don't know tcl.
You can call this script from a batch file as:
tclsh script.tcl
if you have saved the script as script.tcl

Nested FOR with variables

I'm attempting to write a batch script that will go through a list of computers, read a file from the computer, delim the file name, then echo the computer name and the file name result. The issue I'm having is getting the computer name variable to populate in the nested FOR /R command. Here is my script:
#ECHO OFF
SetLocal EnableDelayedExpansion
SET LIST=Computers.txt
FOR /F %%A IN (%LIST%) DO (
FOR /R \\%%A\c$\folder1\folder2 %%B IN (*.txt) DO (
FOR /F "tokens=2 delims=." %%C IN ("%%B") DO (ECHO %%A %%C
)
)
)
EndLocal
The filename is something like RB-C1SRC20160716CL.P17.txt. So the result I am looking for is
MyPCName P17
But I get a blank result. What I have found is that %%A var is being populated from the text file but the %%A var in the FOR /R is not populating. If I ECHO ON the FOR commands I'm seeing FOR /R \%a\folder1\folder2 instead of FOR /R \MyPCName\folder1\folder2. This breakdown is keeping the rest of the script from working properly.
The root directory of a for /R command cannot be given by another for variable (like %%I) nor a variable using delayed expansion (!VAR!), unfortunately. You need to specify it either iterally, by a normally expanded variable (%VAR%) or by an argument reference (%1, %2,...).
A good work-around is to place the for /R loop in a sub-routine and use call to call it from your main routine. The (variable holding the) root path needs to be passed as an argument to call. In the sub-routine it is referred to by an argument reference (like %1).
Take a look at this answer of the post "Get size of the sub folders only using batch command" to see how this can be accomplished.
Another option is to temporarily change into the root directory before the for /R loop, which then defaults to the current working directory. Use pushd"\\%%A\c$\folder1\folder2" to change to the target directory, then put popd behind the for /R loop to return to the former directory.

For loop copying files in command prompt using a substring to name the destination for each file (with delayed expansion)

I have a directory of files and a seperate directory filled with folders with names that correspond to a substring of the file name. I'm trying to cycle through a list of files and for each one, where there is a folder with the corresponding substring name, deposit a copy of the file into it. Where there is no corresponding folder, I need the file to be ignored. This can't be done in a batch file, it needs to be done in command prompt.
I'm having the problem that the initial response to my command
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\%~I J:\test\test_designed_locations\%var:~0,5%\
)
is The syntax of the command is incorrect, due I think to the order of expansion of the command.
....
C:\Windows\System32>(
set var=Ev164_en.wav
copy J:\test\test_audio\en\Ev164_en.wav J:\test\test_designed_locations\%var:~0,5%\
)
The syntax of the command is incorrect
C:\Windows\System32>(
set var=Ev178_en.wav
copy J:\test\test_audio\en\Ev178_en.wav J:\test\test_designed_locations\%var:~0,5%\
)
The syntax of the command is incorrect
...
This would also explain why running the command a second time creates a situation where the substring from the last file is used in all commands, causing every file to be deposited in the last folder and none in the others.
....
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\157_en.wav J:\test\test_designed_locations\Ev225\
)
1 file(s) copied.
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=I
copy J:\test\test_audio\en\158_en.wav J:\test\test_designed_locations\Ev225\
)
1 file(s) copied.
....
I suspect that I need to use delayed expansion to stop environment variables being processed and overwriting each other before use. I've tried adding setLocal enableDelayedExpansion at the start of the command and wrapping the reference to the variable in bangs
setLocal enableDelayedExpansion
for /f %I in ('dir /b J:\test\test_audio\en * ^| find ".wav"') do (
set var=%I
copy J:\test\test_audio\en\%~I J:\test\test_designed_locations\!var:~0,5!\
)
With or without the an escape before the comma, I get
....
C:\Windows\System32>(
set var=Ev164_en.wav
copy J:\test\test_audio\en\Ev164_en.wav J:\test\test_designed_locations\!var:~0,5!\
)
The syntax of the command is incorrect.
....
The variable isn't being processed for its value. I'm starting to wonder if it's actually possible to for-loop through all the files and use a substring from each file name to identify where to put that file, all in one command. Any help much appreciated.
cmd /v /q /c "pushd "j:\test\test_audio\en" && ( for %a in (*.wav) do ( set "I=%~nxa" & if exist "!I:~0,5!\" copy "%a" "!I:~0,5!" ) & popd )"
You can use delayed expansion from command line only if the cmd instance is started with it enabled.
edited to adapt to comments
pushd "j:\test\test_audio\en" && (for %a in (*.wav) do (set "I=%~nxa" & call pushd ^"%I:~0,5^%^" 2>nul &&(copy "%~fa" & popd)) & popd)
Well, it can be done without starting a separate cmd instance to enable delayed expansion, but the needed escaping to use a call to force a second parser evaluation of the line is not very obvious.

Batch Drag and drop files and folders

I'm trying to copy multiple files and folders from a drag and drop selection using a solution I think should look something like this:
mkdir newdir
for %%a in ("%*") do (
echo %%a ^ >>new.set
)
for /f "tokens=* delims= " %%b in ('type "new.set"') do (
SET inset=%%b
call :folderchk
if "%diratr%"=="d" robocopy "%%b" "newdir" "*.*" "*.*" /B /E && exit /b
copy /Y %%b newdir
)
exit /b
:folderchk
for /f tokens=* delims= " %%c in ('dir /b %inset%') do (
set atr=%~ac
set diratr=%atr:~0,1%
)
I've tried throwing together code from the following examples but I'm stuck:
http://ss64.com/nt/syntax-dragdrop.html
Drag and drop batch file for multiple files?
Batch Processing of Multiple Files in Multiple Folders
Handling of special characters with Drag&Drop is tricky, as doesn't quote them in a reliable way.
Spaces are not very complicated, as filenames with spaces are automatically quoted.
But there are two special characters, who can produce problems, the exclamation mark and the ampersand.
Names with an ampersand will not automatically quoted, so the batch can be called this way
myBatch.bat Cat&Dog.txt
This produces two problems, first the parameters aren't complete.
In %1 and also in %* is only the text Cat the &Dog.txt part can't be accessed via the normal parameters, but via the cmdcmdline variable.
This should be expanded via delayed expansion, else exclamation marks and carets can be removed from the filenames.
And when the batch ends, it should use the exit command to close the cmd-window, else the &Dog.txt will be executed and produce normally an error.
So reading the filenamelist should look like
#echo off
setlocal ENABLEDELAYEDEXPANSION
rem Take the cmd-line, remove all until the first parameter
set "params=!cmdcmdline:~0,-1!"
set "params=!params:*" =!"
set count=0
rem Split the parameters on spaces but respect the quotes
for %%N IN (!params!) do (
echo %%N
)
pause
REM ** The exit is important, so the cmd.ex doesn't try to execute commands after ampersands
exit
This is also described in the link you refereneced Drag and drop batch file for multiple files?

Resources