简体   繁体   English

PowerShell-从多个文件名中删除某些字符串

[英]PowerShell - Remove certain string from multiple filenames

I have multiple .mp3 files in the catalogue and want to remove artist's name from their filenames. 我的目录中有多个.mp3文件,并希望从文件名中删除艺术家的名字。 All the files' names contain string 所有文件名均包含字符串

"Adhesive Wombat - " “胶袋熊-”

followed by the song's title. 然后是歌曲的标题。 I want to remove (not replace) every occurence of that specific string in every filename in current folder. 我想删除(而不是替换)当前文件夹中每个文件名中该特定字符串的所有出现。

Not to mention, I've searched for answer on this site and failed to find an elegant and satisfying solution. 更不用说,我已经在该网站上搜索了答案,但没有找到一个优雅而令人满意的解决方案。

This is my first encounter with PowerShell. 这是我第一次接触PowerShell。

As you know what you have is really close. 如您所知,您拥有的确实很近。

Dir | ren -NewName { $_.Name -replace "Adhesive Wombat - ", "" }

You added a stipulation that "Adhesive Wombat" may or may not contain a space. 您添加了“胶粘袋熊”可能包含空格或不包含空格的规定。 -replace uses regular expressions so lets harness that and make that space optional using a ? -replace使用正则表达式,因此可以利用它并使用? 使该空间可选 ? . I am also going to show you the full cmdlet name as supposed to aliases so you are aware of what is happening behind the scenes. 我还将向您显示完整的cmdlet名称(假定为别名),以便您了解幕后情况。 It's hard to see but I tried to highlight the ? 很难看到,但我试图突出显示? in bold for it to "pop". 使其以粗体显示。

Get-ChildItem | Rename-Item -NewName {$_.Name -replace "Adhesive ? Wombat - ", "" }

So that will match both 这样就可以同时匹配

"other text Adhesive Wombat - other text "
"other text AdhesiveWombat - other text "

Also, depending on how much white space there is you could use \\s+ where you have space which will match all consecutive white space. 另外,根据有多少空白,您可以使用\\s+ ,其中有匹配所有连续空白的空间。

From the above answers, the quick working example for simply copy&paste, that worked on win 10 Powershell: 从上面的答案中,可以简单地复制并粘贴的快速工作示例适用于win 10 Powershell:

  1. change directory to your target directory 将目录更改为您的目标目录
  2. get files with eg *.txt or each file . 用* .txt或每个文件获取文件
  3. insert your Strings for replacement 插入字符串进行替换
 cd C:\\.... Get-ChildItem *.* | Rename-Item -NewName {$_.Name -replace "StringtoReplace", "newString"} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM