简体   繁体   English

根据文件内容重命名文件夹中的所有txt文件

[英]Rename all txt files in a folder based on file content

Can someone please help to use PowerShell to rename individual txt files in a folder, each file needs to be renamed based on a keyword inside each individual txt file.有人可以帮忙使用PowerShell重命名文件夹中的单个txt文件,每个文件需要根据每个单独的txt文件中的关键字重命名。

eg例如

c:\temp\1.txt may have a line like Invoice#: 4422 so it needs to be renamed as 4422.txt c:\temp\1.txt可能有类似Invoice#: 4422这样的行,因此需要将其重命名为4422.txt

c:\temp\2.txt may have a line like Invoice#: 5454 so it needs to be renamed as 5454.txt c:\temp\2.txt可能有类似Invoice#: 5454这样的行,因此需要将其重命名为5454.txt

and so on..等等..

I am able to get the invoice number by Regex as我可以通过正则表达式获取发票编号

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

The * C:\temp* folder contains a big number of txt files with different invoice numbers and PS script needs to rename all files. * C:\temp*文件夹包含大量具有不同发票编号的txt文件,PS 脚本需要重命名所有文件。 Thanks,谢谢,

Try this, if it works remove the -WhatIf switch on Rename-Item :试试这个,如果它有效,请移除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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用bash根据正则表达式将文件夹中的所有txt文件拆分为较小的文件 - Splitting all txt files in a folder into smaller files based on a regular expression using bash 重命名文件夹中的所有文件以在 Unix/Mac 上的文件名中包含校验和 - Rename all files within a folder to include checksum in the file name on Unix/Mac 使用regexp基于原始文件夹仅比较和重命名目录中的文件 - compare and rename only files in a directory using regexp based on a original folder 如何将txt文件拆分为多个文件,但不包含具有某些内容的行 - How to split a txt file into multiple files excluding lines with certain content 如何重命名文件夹中的所有文件,删除linux中空格字符后的所有内容? - How to rename all files in a folder removing everything after space character in linux? 用于重命名文件夹中文件以匹配其他文件夹中文件名称的脚本 - Script to rename files in folder to match names of files in another folder 修改 Robocopy 脚本以读取附加到文件夹中文件的编号,添加一个,并重命名正在复制的文件 - Modify Robocopy script to read number appended to files in folder, add one, and rename file that is being copied 重命名文件夹及其子文件夹的文件 - rename files of a folder and its folders children bash:基于正则表达式重命名文件 - bash: rename a file based on a regex 收集* .txt文件的所有链接 - gather all links to *.txt files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM