如何使用 windows powershell 正则表达式删除文件名末尾的一个或多个空格?

how to delete one or more spaces at the end of a filename using windows powershell regex?

我有一个目录,其中包含许多文件名格式错误的文件。其中一些文件名的末尾确实有 "spaces"。其他人在文件名字符串末尾的文件名中有一些关键字。例如 "xxx xxx xxx somewordEng .txt"

我正在尝试使用此脚本摆脱它们,但目前还行不通。文件名 (Basename) 末尾的空格仍然存在,"Eng" 关键字也以某种方式添加到之前的单词中:

dir | Rename-Item -NewName { $_.BaseName.replace("Eng$","").replace(" {2,}"," ").replace("\s$","") + $_.Extension }

.replace("Eng$","")  is supposed to remove the "Eng" keyword if it appears at the END of the filename (basename), seems not working so far.

.replace(" {2,}"," ")   is supposed to replace 2 or more following spaces with just ONE space within the filename, seems not working so far.

.replace("\s$","")    is supposed to remove spaces at the end of the filename, does not work neither. 

我搜索了 powershell 正则表达式示例,但到目前为止似乎没有任何效果。 :( 还看不出问题。

你在这里遇到的问题是字符串方法 .Replace() 不支持正则表达式,而这正是你在这里试图做的。您应该改用替换运算符 -replacethis answer

中详细介绍了这两个选项之间的差异

以下两个例子显示了这种差异

PS C:\Users\mcameron> "Te.t".Replace(".","s")
Test

PS C:\Users\mcameron> "Te.t" -Replace ".","s"
ssss 

你的情况

$_.BaseName -replace "Eng$" -replace " {2,}"," " -replace "\s$"

我们使用了正确的运算符,您仍然可以像上面看到的那样 "chain" 它们。这将删除尾随的单词 "Eng" 和任何尾随的单个白色 space。以及将一组白色space减少为单个space。另外,如果你什么都不替换,那么你可以省略第二个参数。

但是,如果您愿意,可以将它们稍微收紧一点。

$_.BaseName -replace "(Eng|\s+)$" -replace "\s{2,}"," "