首页 > 解决方案 > Powershell根据前缀为文件名添加后缀

问题描述

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

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

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

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

前缀可以是 1 位到 3 位之间的任何值。

由于我是 powershell 新手,我真的不知道如何实现这一点。非常感谢任何帮助。

标签: powershell

解决方案


这是一种方法:

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)"

推荐阅读