0m3r
0m3r

Reputation: 12495

Batch File to rename multiple files and move to folder

I need help with batch file that can rename and move files from my c:\SaveAttachments to multiple folders in C:\Users\Omer\Documents\

I have about 5000 files in c:\SaveAttachments (.pdf, .doc, .xls)

e.g (aacom_880072_4860914.pdf or .doc or .xls) e.g (bbcom_880082_4860914.pdf or .doc or .xls)

rename aacom_880072_4860914 to 880072 and move it to C:\Users\Omer\Documents\aacom

rename bbcom_880082_4860914 to 880082 and move it to C:\Users\Omer\Documents\bbcom

Help on this is greatly appreciated. I hope I have provided sufficient information to see if this is feasible.

FYI I am beginner in coding batch files so comments on the code are greatly appreciated.

Upvotes: 0

Views: 1474

Answers (2)

Magoo
Magoo

Reputation: 80213

@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
set "logfile=U:\logfile.log"
PUSHD "%sourcedir%
>>"%logfile%" echo start at %date% %time%
FOR %%x IN (pdf doc xls) DO (
 FOR /f "delims=" %%a IN (
   'dir /b /a-d "*_*_*.%%x" '
   ) DO (
    FOR /f "tokens=1,2*delims=_" %%m IN ("%%a") DO IF "%%n" neq "" (
    ECHO(MD "%destdir%\%%m"
    >>"%logfile%" ECHO(MD "%destdir%\%%m"
    ECHO(Move "%%a" "%destdir%\%%m\%%n.%%x"
    >>"%logfile%" ECHO(Move "%%a" "%destdir%\%%m\%%n.%%x"
   )
 )
)
POPD
>>"%logfile%" echo end at %date% %time%

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)

The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)

switch to the source directory
For the required extensions, do a directory scan for files with at least 2 underscores and the extension.
tokenise the name to %%m and %%n
(belt-and-braces - ensure %%n isn't empty)
create the directory and move the file.

[edited to include logging as requested] [revised edit : omitted % and include quotes]

Upvotes: 1

user3093115
user3093115

Reputation: 1

If all the files have the same naming convention as you posted this should be relatively easy using a Bash shell script executed within Cygwin.

src='/cygdrive/c/SaveAttachments'
dst="/cygdrive/c/Users/Omer/Documents"
for file in $(find $src -type f)
do
    prefix=${file%%_*}
    if [[ ! -e $dst/$prefix ]]
    then
        mkdir -p $prefix
    fi
    name=$(cut -d_ -f2 $file)
    mv $file $dest/$name
done

I have not tested this so there might be corner cases I missed, but overall you get the idea.

Upvotes: 0

Related Questions