Reputation: 4565
I have written a for
loop in a Win7 batch file which runs through every file in a specified folder:
for /f %%f in ('dir /b C:\some_folder') do (
echo %%f
)
The files are in this format abc_123_1234567.txt
. How can I extract the last set of numbers (i.e. 1234567
) from the filename and put them in a variable?
Upvotes: 1
Views: 2012
Reputation: 79983
for /f "tokens=3delims=_." %%f in ('dir /b C:\some_folder\*') do (
set /a filenum=%%f
echo %%f
)
echo filenum is %filenum%
Provided there is but one file matching the format you've provided
Upvotes: 1
Reputation: 130819
You can solve this nicely using JREN.BAT - a hybrid JScript/batch utility that renames files by performing a regular expression search and replace on the name. JREN.BAT is pure script that will run natively on any Windows machine from XP onward.
I use the /T
test option so that it just lists the original file and the new name, without actually doing a rename. I then use FOR /F to parse the results to get the original name and the extracted number. It requires some arcane syntax to set the delimiter to a quote.
@echo off
for /f tokens^=1^,3^ delims^=^" %%A in (
'jren ".*_\d+_(\d+)\.[^.]*$" "$1" /t /p "C:\some_folder"'
) do (
echo File=%%A Number=%%B
)
Upvotes: 1