Regex 根据文件内容重命名文件夹中的所有txt文件
请有人帮助使用Regex 根据文件内容重命名文件夹中的所有txt文件,regex,powershell,powershell-2.0,powershell-3.0,powershell-4.0,Regex,Powershell,Powershell 2.0,Powershell 3.0,Powershell 4.0,请有人帮助使用PowerShell重命名文件夹中的单个txt文件,每个文件都需要根据每个txt文件中的关键字进行重命名 e、 g c:\temp\1.txt可能有一行类似于发票:4422的内容,因此需要将其重命名为4422.txt c:\temp\2.txt可能有一行类似于发票#:5454的内容,因此需要将其重命名为5454.txt 等等 我可以通过Regex获得发票号 $filecontents -match "INVOICE\#: (\d+):" *C:\temp*文件
PowerShell
重命名文件夹中的单个txt
文件,每个文件都需要根据每个txt
文件中的关键字进行重命名
e、 g
c:\temp\1.txt
可能有一行类似于发票:4422的内容,因此需要将其重命名为4422.txt
c:\temp\2.txt
可能有一行类似于发票#:5454的内容,因此需要将其重命名为5454.txt
等等
我可以通过Regex获得发票号
$filecontents -match "INVOICE\#: (\d+):"
*C:\temp*文件夹包含大量具有不同发票编号的txt
文件,PS脚本需要重命名所有文件。
谢谢,尝试此方法,如果有效,请移除
-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)
}
}
$files=Get ChildItem“c:\temp\*.txt”
$index=[collections.generic.list[string]]::new()
foreach($files中的文件)
{
如果((获取内容$file-Raw)-match'(?尝试此操作,如果有效,请删除-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)
}
}
$files=Get ChildItem“c:\temp\*.txt”
$index=[collections.generic.list[string]]::new()
foreach($files中的文件)
{
如果((获取内容$file-Raw)-match'(?发票号将始终是4位数字?发票#可以是4到9位数字,但是,在上面的正则表达式中,(\d+):能够获取整个发票号,而不管其长度如何发票号将始终是4位数字?发票#可以是4到9位数字,但是,在上面的正则表达式中,(\d+):无论发票的长度如何,都能得到完整的发票号这太完美了,谢谢!没问题:)@M-ACharlotte@M-ACharlotte我在处理可能同名的文件时犯了一个错误,代码已经更新。这太完美了,谢谢!没问题:)@M-ACharlotte@M-ACharlotte我在处理同名文件时犯了一个错误,代码被更新了。