代码之家  ›  专栏  ›  技术社区  ›  Bandito

powershell根据前缀向文件名添加后缀

  •  1
  • Bandito  · 技术社区  · 6 年前

    我有一个目录,其中包含许多已命名的文本文件:

    1Customer.txt
    2Customer.txt
    ...
    99Customer.txt
    

    我正在尝试创建将文件重命名为更符合逻辑的powershell脚本:

    Customer1.txt
    Customer2.txt
    ...
    Customer99.txt
    

    前缀可以是1到3个数字。

    由于我是新来的powershell,我真的不知道如何才能做到这一点。非常感谢您的帮助。

    3 回复  |  直到 6 年前
        1
  •  3
  •   LotPings    6 年前
    • 最重要的前进方向是gci/ls/dir
    • 其中只匹配以数字开头的基名 正则表达式和管道
    • 重命名项并从子匹配生成新名称。

    ls |? BaseName -match '^(\d+)([^0-9].*)$' |ren -new {"{0}{1}{2}" -f $matches[2],$matches[1],$_.extension}
    

    相同的代码没有别名

    Get-ChildItem |Where-Obect {$_.BaseName -match '^(\d+)([^0-9].*)$'} |
        Rename-Item -NewName {"{0}{1}{2}" -f $matches[2],$matches[1],$_.extension}
    
        2
  •  3
  •   henrycarteruk    6 年前

    我相信有更好的方法来处理regex,但下面是一个快速的第一步:

    $prefix = "Customer"
    Get-ChildItem C:\folder\*$prefix.txt  | Rename-Item -NewName {$prefix + ($_.Name -replace $prefix,'')}
    
        3
  •  2
  •   boxdog    6 年前

    有一种方法:

    Get-ChildItem .\Docs -File |
        ForEach-Object {
            if($_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
            {
                Rename-Item -Path $_.FullName -NewName "$($matches.Type)$($matches.Number)$($_.Extension)"
            }
        }
    

    台词:

    $_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
    

    获取文件名(例如“23suppliers.txt”)并对其执行模式匹配,拉出数字部分(23)和“类型”部分(“供应商”),分别命名为“数字”和“类型”。这些由powershell存储在其自动变量中 $matches ,在处理正则表达式时使用。

    然后,我们使用原始文件的详细信息重建新文件,例如文件的扩展名( $_.Extension )以及匹配的类型( $matches.Type )和数字( $matches.Number ):

    "$($matches.Type)$($matches.Number)$($_.Extension)"