【问题标题】:Removing multiple consecutive periods from file names从文件名中删除多个连续句点
【发布时间】:2019-05-28 19:26:56
【问题描述】:

我正在为 SharePoint 迁移清理文件共享,并且我正在编写一个脚本来删除或替换文件名中不需要的字符。我正在努力删除多个连续的时期(文件..example.txt 作为我正在处理的示例)。

我能够使用下面的简单替换脚本来处理所有其他令人反感的字符,但是在尝试替换双句点错误时脚本失败了。

dir -recurse | rename-item -NewName {$_.name -replace ".." , ""}

我希望名为 file..example.txt 的文件变成 fileexample.txt,但没有任何变化。

【问题讨论】:

  • -replace 使用正则表达式,句点是元字符。你想要的是$_.name -replace "\.+", ".",它将用一个替换任何一组句点。前任。 "hello..this .....is ... me." -replace "\.+", "." 会给hello.this .is . me.
  • 同意@Matt 的替代正则表达式是Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '\.+(?=\.)'} 它不需要替换字符串,因为它会删除除最后一个之外的所有后续点作为lookahead

标签: powershell


【解决方案1】:

正如马特在 cmets 中提到的,-replace 使用正则表达式。在正则表达式中,. 字符是表示任何单个字符的通配符。要实际选择一个点,您必须使用\.

选择带有两个或更多点的任何内容的正则表达式是\.\.+ (RegExr)

因此,您的命令应该是:

dir -Recurse | Rename-Item -NewName {$_.name -replace "\.\.+" , ""}

但是,dirGet-ChildItem 的别名。在编写脚本时尽可能避免使用别名是一种很好的做法,因为这可能会导致您的脚本在某些环境中无法运行。考虑到这一点,您的命令应该是:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace "\.\.+" , ""}

【讨论】:

    【解决方案2】:

    您可以使用 .replace() 代替,而不必担心正则表达式。请注意,Rename-Item 正在使用延迟绑定脚本块https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parameters?view=powershell-5.1

    Get-Childitem -Recurse -Filter *..* | 
      Rename-Item -NewName { $_.Name.Replace('..','.') } -WhatIf
    

    【讨论】:

    • 只要您只想替换两个连续的点就可以了,这可能是也可能不是@daustindev 需要的
    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多