I am trying to make a batch file, that will:
Ask for a directory (where many files are contained)
Ask for a second directory (this is the location where the batch will create directories for each file, and then copy each file to its own directory)
Number of characters to remove from the right hand side of the created directory. (Eg, two documents 'NewDoc_Ver1' and 'NewDoc_Ver2', would both be copied into the same directory 'NewDoc').
Below are some similar questions that might help.
https://superuser.com/questions/1138283/batch-script-for-moving-files-to-the-same-name-folder
How do you get the string length in a batch file?
batch files calling %~1 and getting the variable's current value/string
https://ss64.com/nt/syntax-substring.html
I am currently stuck on trying to get the 'String Left' to work with a dynamic number. (I haven't looked at how to put in a user input yet) Any help would be great.
@echo off
setlocal enabledelayedexpansion
set folderpath=C:\Users\james.shaw\Desktop\R2
for %%f in (%folderpath%\*.*) do (
set "foldername=%%~nf"
set f1=!foldername!
call :strlen folderlength foldername
REM set JS1=%%foldername:~0,!folderlength!%%
set JS1=!f1!:~0,!folderlength!
md !JS1!
REM md "!foldername:~0,!folderlength!!" >nul 2>&1
move "%%f" "!foldername:~0,!folderlength!!"
pause
)
goto :eof
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
Update:
below is a batch I have found that is similar to what I am looking for (I have lost the web URL), however this only runs within the same directory that the batch file does, and doesn't allow for truncating the created directories: I am still interested in learning what I was doing wrong in my original attempt.
@echo off
setlocal EnableDelayedExpansion
set RemoveStrings="[ www.AnnoyingSpam.com ]",
Rem RemoveStrings variable notes:
Rem Surround strings to remove with double quotes.
Rem Separate each separate string to remove with a comma.
goto :main
: trim_leading_spaces VariableName
setlocal EnableDelayedExpansion
set "_=!%~1!"
set _=%_:"=%
: trim_leading_spaces__while
if "%_:~0,1%"==" " ( set "_=%_:~1%"& goto :trim_leading_spaces__while)
endlocal & set "%~1=%_%"
goto :eof
: trim_trailing_spaces VariableName
setlocal EnableDelayedExpansion
set "_=!%~1!"
set _=%_:"=%
: trim_trailing_spaces__while
if "%_:~-1%"==" " ( set "_=%_:~0,-1%"& goto :trim_trailing_spaces__while)
endlocal & set "%~1=%_%"
goto :eof
: main
for /f "delims=" %%I in ( dir /b /a:-d ^| findstr /vixc:"%~nx0" ) do (
Set file = "%%~I"
for %%J in (%REMOVESTRINGS%) do set "file=!FILE:%%~J=!"
call :trim_leading_spaces file
call :trim_trailing_spaces file
for %%J in ("!FILE!") do set "NewDirName=%%~nJ"
md "!NEWDIRNAME!"
ren "%%~I" "!FILE!"
move "!FILE!" "!NEWDIRNAME!"
)