【问题标题】:Rename all txt files in a folder based on file content根据文件内容重命名文件夹中的所有txt文件
【发布时间】:2021-08-02 00:48:51
【问题描述】:

有人可以帮助使用PowerShell 重命名文件夹中的单个txt 文件,每个文件都需要根据每个txt 文件中的关键字重命名。

例如

c:\temp\1.txt 可能有类似 Invoice#: 4422 这样的行,因此需要将其重命名为 4422.txt

c:\temp\2.txt 可能有类似 Invoice#: 5454 这样的行,因此需要将其重命名为 5454.txt

等等..

我可以通过正则表达式获取发票号码

$filecontents -match "INVOICE\#: (\d+):"

*C:\temp* 文件夹包含大量具有不同发票编号的txt 文件,PS 脚本需要重命名所有文件。 谢谢,

【问题讨论】:

  • 发票号码总是是 4 位数字?
  • Invoice# 可以是 4 到 9 位数字,但是,在上述正则表达式中, (\d+): 能够获取完整的发票编号,无论其长度如何

标签: regex powershell powershell-2.0 powershell-3.0 powershell-4.0


【解决方案1】:

试试这个,如果有效,请移除 Rename-Item 上的 -WhatIf 开关:

$files = Get-ChildItem "c:\temp\*.txt"
$index = [collections.generic.list[string]]::new()

foreach($file in $files)
{
    if((Get-Content $file -Raw) -match '(?<=Invoice#:\s)\d+')
    {
        $invoiceNumber = $matches[0]
        
        if($index.contains($invoiceNumber))
        {
            Write-Warning "File with name $invoiceNumber.txt already exists. Skipping."
            continue
        }

        "Renaming {0} to $invoiceNumber.txt" -f $file.Name
        $file | Rename-Item -NewName $invoiceNumber.txt -WhatIf
        $index.Add($invoiceNumber)
    }
}

【讨论】:

  • 没问题 :) @M-ACharlotte
  • @M-ACharlotte 我实际上在处理可能的同名文件时犯了一个错误,代码已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多