更新时间:2023-02-06 19:15:37
假设所有输入文件名在相同位置具有相同数量的标记和相同的分隔符:
Assuming that all input filenames have the same number of tokens with the same separators in the same positions:
Get-ChildItem -Filter *.csv | Rename-Item -NewName {
(($_.Name -split '[-_]')[0, 10, 11, 12] -join '-') + '.csv'
} -WhatIf
-WhatIf
预览 重命名操作;删除它以执行实际重命名.
-WhatIf
previews the renaming operations; remove it to perform actual renaming.
通过分隔符将文件名拆分为标记避免了复杂的正则表达式;PowerShell 灵活的数组切片功能可以轻松地将目标文件名与通过其索引访问的感兴趣的标记拼凑在一起.
Splitting the filename into tokens by separators avoids complex regexes; PowerShell's flexible array slicing makes it easy to piece together the target filename from the tokens of interest accessed by their indices.
也就是说,如果你想用 -replace
和一个复杂的正则表达式来实现:
That said, if you wanted to do it with -replace
and a complex regex:
Get-ChildItem -Filter *.csv | Rename-Item -NewName {
$_.Name -replace '^([^-]+).*?-(\d[^_]+).*', '$1-$2.csv'
} -Whatif
此解决方案不假设要提取的第二个标记的固定位置 - _
之前的那个 - 而是通过 -
后跟一个数字来标识其开始(\d
).
This solution doesn't assume a fixed position of the 2nd token to extract - the one before _
- and instead identifies its start by a -
followed by a digit (\d
).