例如我的文件是
-a---- 10/05/2018 22:15 12550016 01. Eat the Elephant (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 14163840 02. Disillusioned (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 9547648 03. The Contrarian (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 11272064 04. The Doomed (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 10649472 05. So Long, and Thanks for All the Fish (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 9961344 06. TalkTalk (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 12201856 07. By and Down the River (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 9183104 08. Delicious (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 5074816 09. DLB (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 12578688 10. Hourglass (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 13938560 11. Feathers (2018_07_06 06_26_52 UTC).mp3 -a---- 10/05/2018 22:15 16031616 12. Get the Lead Out (2018_07_06 06_26_52 UTC).mp3
我打算从文件中删除方括号,方括号以及第一个方括号之前的空格中的所有文本。
我在下面的PowerShell中使用正则表达式尝试了此脚本,但是它没有按预期工作。
Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name.Replace(" \((.*?)\)", "")}
答案 0 :(得分:1)
PowerShell的Replace
运算符接受正则表达式。
Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -Replace " \((.*?)\)", "" }
请参阅Rename-Item与-Replace
运算符的组合。
({$_.Name.Replace
只是在进行纯文本/字符串替换。)
答案 1 :(得分:0)
因为您要删除每一行的特定部分,所以我使用了一个捕获括号,该括号允许在$ Matches变量中捕获每个部分,并且由于捕获括号只有一个块,因此我使用索引1来访问匹配项在$ Matches变量中。
$ Matches变量的结果如下所示
$Matches
变量的结果看起来像这样
Name Value
---- -----
1 (2018_07_06 06_26_52 UTC)
0 -a---- 10/05/2018 22:15 13938560 11. Feathers (2018_07_06 06_26_52 UTC).mp3
要执行替换,我检查$ chain变量中是否存在与正则表达式模式匹配的部分。如果是这种情况,我将执行替换
$chain = "-a---- 10/05/2018 22:15 13938560 11. Feathers (2018_07_06 06_26_52 UTC).mp3"
if($chain -match '.+(\s\(.+\)).+'){
$new_filename = $chain.Replace($Matches[1], "")
}
替换$new_filename
后将包含
-a---- 10/05/2018 22:15 13938560 11. Feathers.mp3
因为您正在使用Get-ChildItem -Recurse
获取文件列表,所以可以将结果保存在变量中并遍历结果,并检查数组中的每个元素是否都有一个缓存部分并进行替换