问题描述
我正在尝试从多个文件的末尾删除名称为“-xx_xx”的部分。我正在使用它,效果很好。
dir |重命名项-NewName {$ _。Name -replace“-xx_xx”,“”}
但是,还有其他部分,例如:
“-yy_yy” “-zz_zz”
该如何一次删除所有这些,而不是一次又一次地运行以更改要删除的名称的一部分?
解决方法
最简便的方法
如果需要,您可以继续输入-replace
语句直到奶牛回家。
$myLongFileName = "Something xx_xx yy_yy zz_zz" -replace "xx_xx","" -replace "yy_yy"
更多简洁语法
如果每个文件都包含这些,则还可以将要替换的部分排列成这样,只需用逗号分隔即可。
$stuffWeDontWantInOurFile =@("xx_xx","yy_yy","zz_zz")
$myLongFileName -replace $stuffWeDontWantInOurFile,""
另一种方式
如果文件元素之间用空格或破折号或可预见的分隔,则可以在其上拆分文件名。
$myLongFileName = "Something xx_xx yy_yy zz_zz"
PS> $myLongFileName.Split()
Something
xx_xx
yy_yy
zz_zz
PS> $myLongFileName.Split()[0] #select just the first piece
Something
对于空格,请使用Spit()
方法,该方法内部无重载。
如果是破折号或其他字符,则可以像Split("-")
那样提供。在这两种技术之间,您应该能够做自己想做的事。
如果您所说的模式 - xx_xx
始终位于文件名的末尾,我建议使用类似以下的内容:
Get-ChildItem -Path '<TheFolderWhereTheFilesAre>' -File |
Rename-Item -NewName {
'{0}{1}' -f ($_.BaseName -replace '\s*-\s*.._..$'),$_.Extension
} -WhatIf
如果您对控制台中显示的结果感到满意,请删除-WhatIf
开关
结果:
D:\Test\blah - xx_yy.txt --> D:\Test\blah.txt D:\Test\somefile - zy_xa.txt --> D:\Test\somefile.txt
正则表达式详细信息:
\s Match a single character that is a “whitespace character” (spaces,tabs,line breaks,etc.) * Between zero and unlimited times,as many times as possible,giving back as needed (greedy) - Match the character “-” literally \s Match a single character that is a “whitespace character” (spaces,giving back as needed (greedy) . Match any single character that is not a line break character . Match any single character that is not a line break character _ Match the character “_” literally . Match any single character that is not a line break character . Match any single character that is not a line break character $ Assert position at the end of the string (or before the line break at the end of the string,if any)