使用 Windows Powershell 删除文件名开头的随机字符串

问题描述 投票:0回答:1

我有几百个文件想重命名

在文件名的开头都有随机字符串,但在这个例子中都有一个常量“文件”这个词

那么我将如何从中得到

huhukifauduigui9983hodhohhh File 01 [145dde].ext
ljdwidnjncjbbbjbk File 55 [wniw].ext
wdwjbnkjbkjbiuiuiubi File 24 [wdwxxx].ext
plxwjijiwi File 14 [wddbb].ext

到这个

File 01 [145dde].ext
File 55 [wniw].ext
File 24 [wdwxxx].ext
File 14 [wddbb].ext

提前谢谢你

我唯一能想到的是一个powershell命令,但真正知道如何替换特定的字符串

windows powershell rename file-rename
1个回答
0
投票

使用

-replace
,PowerShell 的 regex-based string-replacement operator:

Get-ChildItem -Filter *.ext |
  Rename-Item -NewName { $_.Name -replace '^.*\b(?=File)' } -WhatIf

注意:上面命令中的

-WhatIf
常用参数previews操作。删除
-WhatIf
并在您确定操作将执行您想要的操作后重新执行。

Regex

^.*\b(?=File)
匹配文件名 (
*
) 的
start
处的任意数量 (.) 个字符 (
^
)(可能没有),但不包括(由于使用了前瞻断言,
(?=…)
)单词
File
,它必须出现在单词边界(
\b
)。
有关正则表达式的更详细解释以及使用它进行实验的能力,请参阅this regex101.com page.

由于没有给出替换操作数,因此隐含了空字符串,从而有效地删除了匹配部分。

请注意,如果给定文件的名称与模式不匹配,其名称将保持原样。

还要注意使用delay-bind脚本块

Rename-Item
-NewName
参数,以便动态根据
Get-ChildItem
发出的每个文件信息对象确定新文件名

© www.soinside.com 2019 - 2024. All rights reserved.