GreenAsJade
GreenAsJade

Reputation: 14685

Batch file: extract wildcard part of file name from input parameter

I have a batch file being passed a wildcarded file name:

mybat.bat foo\bar\*.stuff

How can I get

"*.stuff"

into a variable?

I know how to do

set the_path=%~p1
set the_file=%~n1

but this results in the_file being one of the files that matched, not the string wildcard spec.

Upvotes: 1

Views: 889

Answers (3)

user15261314
user15261314

Reputation: 7

Use the right tool for the job. This is a job for a Regular Expression!

FOR /F "tokens=*" %%F IN ('POWERSHELL -command "'%~1' -Replace '([A-Z]:)?(.*\\)*', ''"') DO ECHO The path is %~dp1 and the filename is %%F

The Regular Expression used in this command matches an optional drive letter and colon, followed by zero or more strings ending with "". Everything following the last "" is the part we want to keep. The PowerShell "-Replace" parameter replaces the matched string (the drive and path) with the empty string, leaving only the filename.extension. If filename.extension contains wildcards, they are left intact.

Upvotes: 0

aschipfl
aschipfl

Reputation: 34979

String substitution as mentioned in this answer works fine as long as the file pattern starts with *.

However, the following code extracts the file name from the path independent from the *; rather it strips everything up to \ from the left side of the string in a loop until no more \ are encountered.
There is a second loop that handles the special case when a file is specified in the current directory of a drive, for instance D:test_???.log:

set "file=%~1"
:LOOP1
if not "%file%"=="%file:*\=%" set "file=%file:*\=%" & goto :LOOP1
:LOOP2
if not "%file%"=="%file:*:=%" set "file=%file:*:=%" & goto :LOOP2
echo "%file%"

Upvotes: 2

Stephan
Stephan

Reputation: 56228

echo %1
set x=%~1
set x=%x:**=*%
echo %x%

string substituion: replace *<string> with <string>, (being <string> = * in your case)

Upvotes: 3

Related Questions