Reputation: 121
I have files names like this:
"Jeff W ACE #20495 Bund Job Report Submitted 9 16 2020 -oOo-.msg"
"Miguel M ACE #21462 Ficus Job Report Submitted 9 15 2020 -oOo-.msg"
"Sandy U ACE #6624 99 Twin Crossing Job Report Submitted 9 17 2020 -oOo-.msg"
I need to move them to a directory based on the 4 or 5 digit number after the # in the name. I found a batch file but it needs to have the directory name at the same location in the file name and the same length.
@echo off &setlocal
for /f "delims=" %%i in ('dir /b /a-d *.text') do (
set "filename1=%%~i"
setlocal enabledelayedexpansion
set "folder1=!filename1:~0,1!"
mkdir "!folder1!" 2>nul
move "!filename1!" "!folder1!" >nul
endlocal
)
How can I modify this batch file to search for the 4 or 5 digit number instead of the number having to be at a fixed place within the name? Thanks!
Upvotes: 0
Views: 607
Reputation: 34899
I would probably use the following code to achieve your goal:
rem /* Loop through (unhidden) files whose names contain the sequence ` #`;
rem split the file names at the `#` character then (there should be only one);
rem the part before `#` is available in `%%E`, the part after `#` in `%%F`: */
for /F "tokens=1* eol=# delims=#" %%E in ('dir /B /A:-D-H-S "* #*.msg"') do (
rem // Split off the first space-separated word from the second name part:
for /F "eol= " %%G in ("%%~nF") do (
rem /* Use that word as the name of a sub-directory and create it
rem (` 2> nul` suppresses error messages when it already exists): */
md "%%G" 2> nul
rem /* Actually move the currently iterated file into the sub-directory
rem (there will appear a prompt when the target file already exists;
rem to avoid that, use the `/Y` option of `move` to force overwriting,
rem or put `if not exist "%%G\%%E#%%F" ` in front of `move` to avoid
rem overwriting; append ` > nul` to suppress text `1 file(s) moved.`): */
move "%%E#%%F" "%%G\"
)
)
Upvotes: 1