批处理:变量 %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 !"
使用 PowerShell 的运算符来提取前缀更简单、更可靠
-replace
:笔记:
以上不需要
setlocal enabledelayedexpansion
。通过使 PowerShell 命令将
title
变量作为环境变量引用,可以避免将变量的值直接嵌入命令中$env:title
时可能出现的问题。title