批处理:我在变量%filename%中有一个字符串。我需要检查它是否有已知变量 %year%,并使用它来将字符串简化为标题。
示例:
The Grand Strategy (1999) whatever.pdf
...会变成...
The Grand Strategy
...所以重点是使用年份作为截止点,取出年份和文件名的其余部分。该脚本必须适用于任何未知的文件名。
我的代码:
for /f "delims=" %%r in ('powershell -command "if ('!title!' -match '\b(19|20)\d{2}\b') { echo $matches[0] } else { echo No match }"') do set "year=%%r"
set title=!title: (%year%)=& rem !"
-replace
运算符为您提取前缀更简单、更可靠:
@echo off
:: Sample title
set "title=The Grand Strategy (1999) whatever.pdf"
for /f "usebackq delims=" %%r in (`
powershell -NoProfile -Command "$env:title -replace ' *\((19|20)\d{2}\).*'"
`) do set "title=%%r"
:: Diagnostic output to verify the result.
echo "%title%"