Reputation: 23
Morning,
Id like to read all folder names from a directory but then extract part of this name to a text file.
E.g.
Folder \users\music has these folders within: Tes125559-blah345534 tes125558-blah235235
Id like to extract 3 characters in until the -, so for Tes125559-blah345534 im after just the 125559 to be put into a text file.
Its always 3 chars in then a 6 digit numeric value that needs grabbing
Any help is very appreciated, so far I only read the directory:
dir /b > file.txt
Upvotes: 0
Views: 75
Reputation: 2960
Something like the following should do the trick:
@echo off
setlocal enabledelayedexpansion
if exist file.txt del file.txt
for /d %%a in (*) do (
set DIR=%%a
echo !DIR:~3,6!>>file.txt
)
The for
loop iterates over all directories (in the current directory). For each one, it stores the directory name in DIR
and then uses a "sub-string" syntax to extract six characters starting at the fourth (the 3
is because it counts from zero -- see SET /?
for more information).
The use of !
around this construct (and enabledelayedexpansion
at the top of the script) is because the normal way of referring to environment variables (with %
) would not re-evaluate the value of %DIR%
each time around the for
loop (see cmd /?
for more details).
Because each directory is appended to the file.txt
, we delete it before we start (if it exists).
Upvotes: 1