Monday, October 4, 2010

A Batch that Parses Filenames in a Directory

This batch file is deceptively simple. What does it do? Absolutely nothing. However, each filename within a directory is parsed and made available for use. A programmer may add commands to manipulate each file within the :process subroutine. I created this for my brother, who needed this particular capability. Many thanks to innumerable strangers on the Internet that have written guides and tutorials on Batch language, because I often forget the syntax of the FOR command, which must be the most complicated in Batch language. If it were not for Google, I would be tempted to abandon Batch altogether, as most programmers have. But there is something cool about running a program straight from Windows that doesn't require compilation or any additional interpreter.

---------

@echo off
cls

dir /b /a-d *.mp3 > temp.txt
if not exist temp.txt echo No Mp3 files found!
if not exist temp.txt pause
if not exist temp.txt exit
echo Temporary file has been created.
pause

rem -----------------------------------------------------
rem The following FOR statement must be one line, not two
rem (Beware of Blogger's word wrap.)
rem -----------------------------------------------------
FOR /F "usebackq tokens=1,2 delims=-" %%a in (temp.txt) DO call :process "%%a" "%%b"
rem -----------------------------------------------------
echo.
echo Alas, We Have Reached The End.
echo.
pause
exit

:process
set VAR1=%1
rem Trim quotes
for /f "useback tokens=*" %%a in ('%VAR1%') do set VAR1=%%~a
echo VAR1=%VAR1%

set VAR2=%2
rem Trim quotes
for /f "useback tokens=*" %%a in ('%VAR2%') do set VAR2=%%~a
echo VAR2=%VAR2%

set filename=%VAR1%- %VAR2%
echo %filename%
pause
goto :EOF

by igor 04:20 4 replies by igor 09:32 0 comments

No comments:

techlorebyigor is my personal journal for ideas & opinions