【问题标题】:how to delete one or more spaces at the end of a filename using windows powershell regex?如何使用 windows powershell regex 删除文件名末尾的一个或多个空格?
【发布时间】:2015-10-14 00:10:05
【问题描述】:

我有一个目录,其中包含许多文件名格式错误的文件。其中一些确实在文件名的末尾有“空格”。其他人在文件名字符串末尾的文件名中包含一些关键字。例如“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 不是 -replace 后者支持正则表达式。前者是简单的通配符。
  • 我想补充一点,你完全可以使用.Trim() 方法来做到这一点。

标签: regex windows powershell scripting


【解决方案1】:

您在这里遇到的问题是字符串方法.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$"

我们使用了正确的运算符,您仍然可以像上面看到的那样“链接”它们。这将删除尾随单词“Eng”和任何尾随单个空格。以及将一组空格减少为一个空格。此外,如果您不替换任何内容,则可以省略第二个参数。

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

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

【讨论】:

  • 嗯.. 好的,谢谢。但是我怎样才能将这两种方法组合成一行呢?我尝试了将“-replace regex”与“.replace()”方法结合使用的建议,但 atm 仍然失败(或者只是部分工作)。在此处查看此示例: dir |重命名项目 -NewName { $_.BaseName.replace("nastyKeyword1","").replace("nastyKeyword1","") -replace "Eng$" -replace " {2,}"," -replace "插入该位置的 \s$" + $_.Extension } 会给我一个错误。但我想在那个位置进行替换,这样我就不必关心扩展了。我该如何解决这个问题?
  • 或者我可以做一些事情 {{{ $_.BaseName -replace "(Eng|\s+)$" -replace "\s{2,}"," " .replace("nastyKeyword1 ","").replace("nastyKeyword2","") }}} 不知何故 ??
  • @AxelWerner 不要像这样嵌套花括号。它们表示一个脚本块。您应该能够尝试当前的逻辑,但请改用()。你也可以-replace "NastyKeyword1|NastyKeyword2|andsoon"
猜你喜欢
  • 2018-11-22
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 2022-11-28
  • 2015-10-01
  • 1970-01-01
相关资源
最近更新 更多