Unmesh Ghatbandhe
Unmesh Ghatbandhe

Reputation: 45

How to get first (last modified) folder name in given path in batch file

How to get first (last modified) folder name from \\demo\Test\test1\?
If the first folder is test-new_20170908.2 how do I get test-new_20170908.2 and only the 20170908.2 part?

This is what I've done so far:

@echo off
set MYDIR=\\demo\Test\test1\
set MYDIR1=%MYDIR:~0,-1%
for %%f in (%MYDIR1%) do set myfolder=%%~nxf
echo %myfolder% > folderPath.txt

This code gives me test1 but I want the very first folder name inside given path and this does not work as per my specification.
Can anybody help me?

Upvotes: 1

Views: 1215

Answers (2)

Andre Kampling
Andre Kampling

Reputation: 5630

The following script will sort all directories (/a:d) under demo\Test\test1 by the last write date (/o:-d /tw) and just save the second token of the name separated by _: name_date which is date.

Batch script:

@echo off

set "MYDIR=demo\Test\test1"

rem sort directories by date (last write)
for /f "tokens=*" %%f in ('dir "%MYDIR%" /a:d /o:-d /tw /b') do (
   rem use second token after _ in name
   for /f "tokens=2 delims=_" %%a in ('echo %%f') do ( set "myfolder=%%a" )
   goto :found
)

:found

echo %myfolder%

Output:

20170908.2

Command reference links from ss64.com:

Upvotes: 4

Magoo
Magoo

Reputation: 80213

@ECHO OFF
SETLOCAL
set MYDIR=\\demo\Test\test1\
set MYDIR1=%MYDIR:~0,-1%
SET "mydir=U:\sourcedir\"
FOR /d %%a IN ("%mydir%\*") DO SET "myfolder=%%~nxa"&GOTO found
:found
echo %myfolder%

GOTO :EOF

I overrode you setting of mydir to a directory that is more convenient in my system.

Look for all of the directories (for /d) matching the supplied mask (the \ here makes it irrelevant whether you include a terminal \ in the value of mydir (my preference is to omit that terminal \) then treat the returned directoryname as a filename and select the name and extension using the for name-partitioning operators; assign the result to the variable and force exit from the for with a goto once the first assignment as occurred.

Upvotes: 0

Related Questions