saurabh swarpal
saurabh swarpal

Reputation: 11

batch script to read a specific pattern and sort the files in the new folder

I have a folder where I have millions of file somewhat like

XXXXXX_156_1400093_20160507011119.psv

From this format I want a batch script which may ask me to input date in format yyymmdd seach for that date in the file name. Create a folder with the date and move all the files related to the specific date there.

I tried multiple examples and since I dont know scripting please help me. Regards Saurabh

I have tried the following code:

@ECHO on
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION

SET "sourcedir=C:\Users\sswarpal\Desktop\files"
PUSHD %sourcedir%
FOR /f "tokens=1,2,3,4 delims=_" %%a IN (
 'dir /b /a-d "*.psv"'
 ) DO (  
 MD %%a
 MOVE "%%a %%b" .\%%a\
)
POPD
GOTO :EOF

Upvotes: 0

Views: 465

Answers (2)

Filipus
Filipus

Reputation: 540

Save the following code in a batch file (e.g. myMover.bat). When running the file from a command line window, supply the date you want as the sole parameter on the command line, as in:

myMover 20160508

Here's the code:

@ECHO off
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION
if "%1"=="" goto syntax
SET sourcedir="C:\Users\sswarpal\Desktop\files"
PUSHD %sourcedir%
if not exist %1 MD %1
FOR /F %%i IN ('dir /b *_%1*.psv') DO move "%%~ni%%~xi" %1
POPD
goto :eof

:syntax
Echo.
Echo Syntax:
Echo %0 YYYYMMDD
Echo.

Upvotes: 0

Stephan
Stephan

Reputation: 56238

a batch script which may ask me to input date in format yyymmdd seach for that date in the file name. Create a folder with the date and move all the files related to the specific date there.

Keep it simple. Use wildcards with move instead of a complicated for loop

set /p "day=Enter Date (YYYYMMDD): "
md %day% 2>nul
move "*%day%??????.psv" %day%

If you want to do it automatic (like your code suggests): just using random parameters won't help (token 1 %%a is XXXXXX, but you want to create a subdir with the date (part of token 4)). Your parameters to move seems totally random.
Try this instead:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\Users\sswarpal\Desktop\files"
PUSHD %sourcedir%
FOR /f "tokens=1,2,3,4 delims=_" %%a IN ('dir /b /a-d "*.psv"') DO (  
   set day=%%d
   set day=!day:~0,8!
   echo md !day! 2>nul
   echo MOVE "%%a_%%b_%%c_%%d" .\!day!\
)
popd

Remove the words echo when the output looks like what you want.

Upvotes: 1

Related Questions