Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script to Get First Filename from a directory

Tags:

batch-file

My function needs the first filename from a particular directory to process some tests using the first file, on completing tests delete first file from directory

I tried as below

FOR /R \\<My Folder> %F in (*.zip*) do echo ~nF  >%test_list%
set /p firstline=%test_list%
echo %firstline% 


FOR /F "tokens=*" %%A IN ('dir %test_firmware_dir% /b/s ^| find /c ".zip"') DO SET 
 count=%%A
  echo %count%
 :test_execution
  if %count% NEQ 0 (
  echo ON
  dir /b %test_firmware_dir%\*.zip >%test_firmware_list%
 set /p firstline=<%test_firmware_list%
 set /a filename=%firstline:~0,-4%
  Echo %filename%
  Echo *********************************************************
 Echo "Now running batch queue tests with %filename%"
  Echo ********************************************************

it is showing last element any procedure to get first element ??

like image 927
channa Avatar asked Aug 09 '12 12:08

channa


2 Answers

An alternative is to use goto (breaks FOR loops) after you have your first file:

FOR %%F IN (%test_firmware_dir%\*.zip) DO (
 set filename=%%F
 goto tests
)
:tests
echo "%filename%"

And it could run (a little bit) faster in some cases as it doesn't have to go through the whole directory.

like image 179
Drarakel Avatar answered Nov 06 '22 11:11

Drarakel


Assuming you mean the 1st file when sorted alphabetically; then given that you traverse the list overwriting the last value you will as you say capture the last file, instead control the sort order;

for /f "delims=" %%F in ('dir %test_firmware_dir%\*.zip /b /o-n') do set file=%%F
echo 1st alpha file is %file%
like image 20
Alex K. Avatar answered Nov 06 '22 11:11

Alex K.