dr_rk
dr_rk

Reputation: 4565

Windows batch file match prefix and suffix in filenames

Within an Windows batch file, is it possible to extract somestring when files are named this way:

prefix_somestring.txt
somestring_suffix.txt 

Assuming the underscore _ separating the prefix or suffix. The context is to iterate through all files in a folder and return somestring for each file.

Upvotes: 1

Views: 2048

Answers (1)

Infinite Recursion
Infinite Recursion

Reputation: 6557

You can replace the _ with space. Then the filename string will be two words. Now run a for loop and store the two words in two variables.

Please excuse brevity due to typing through mobile app.

for %%a in ("%cd%\*.txt") do (
set myfile=%%~nxa
set myfile=!myfile:_= !

set part1=""
set part2=""
for %%i in (%myfile%) do (
    if "%part1%"=="" (
        set part1=%%i
    ) else (
        set part2=%%i
    )
)
echo %part1% %part2%
)

Upvotes: 1

Related Questions