删除部分文件名并将一种文件类型的名称赋予另一种文件类型

删除部分文件名并将一种文件类型的名称赋予另一种文件类型

假设我有一个文件夹,rar里面pdf有一组人的文件。每个人都有一个唯一的代码,并且他/她与两个文件相关联

Full name <unique code>_dummy text to remove.rarsome text <unique code>_another dummy text to remove.pdf

例如,

First Man 11e2345_some text to remove.rara person 11e2345_another text to remove.pdf

Second Lady 66t7899_remove this text.rardifferent person 66t7899_dummy text to remove.pdf

因此,我有两个问题:

1-对于rar文件,如何通过删除唯一代码后以下划线开头的所有文本来重命名文件?

2-重命名rar文件后,如何通过查找为每个pdf文件赋予与其对应文件相同的名称?rar<unique code>

我希望的结果应该是

First Man 11e2345.rarFirst Man 11e2345.pdf

Second Lady 66t7899.rarSecond Lady 66t7899.pdf


更新

如果唯一代码包含字母和数字,例如,14e0123并且我知道它的长度(例如7),如何编辑 Karthick 代码的这一部分以适应?因为$ID = $_.BaseName -replace "[^0-9]", "" 将在查找之前删除所有字母。

Get-ChildItem "*.rar" | % {

    $BaseName_rar = $_.BaseName
    # Find the ID by replacing all non-digit characters in BaseName string of the 'rar' file with empty string
    # This effectively returns the ID which are the only numbers expected in the filename 
    $ID = $_.BaseName -replace "[^0-9]", ""

    Get-ChildItem "*$ID.pdf"  | % { Rename-Item $_.FullName -NewName ($BaseName_rar + $_.Extension) }

}

答案1

下面的代码应该可以帮助您解决这个问题。

$sourceFolderPath = "D:\source"
Set-Location $sourceFolderPath

# 1 Replace the part of filename from underscore character with empty string
Get-ChildItem "*.rar", "*.pdf" | % { Rename-Item $_.Fullname -NewName (($_.BaseName -replace "_.*","") + $_.Extension) }

<# 2 ForEach 'rar' file object,
    - Get the ID
    - Get the corresponding 'pdf' by ID
    - Rename the 'pdf' with BaseName of 'rar'
#>
Get-ChildItem "*.rar" | % {

    $BaseName_rar = $_.BaseName
    # If ID is just numbers
    # Find the ID by replacing all non-digit characters in BaseName string of the 'rar' file with empty string
    # This effectively returns the ID which are the only numbers expected in the filename 
     # $ID = $_.BaseName -replace "[^0-9]", ""

    # UPDATE: If ID begins with a number and has a total length of 7
    $ID = & { 
        $_.BaseName -match "(\d.{6})" | Out-Null
        $matches[0] 
    }
    
    Get-ChildItem "*$ID.pdf"  | % { Rename-Item $_.FullName -NewName ($BaseName_rar + $_.Extension) }

}

更新

假设 ID 以数字开头,总长度为 7,可以将$ID赋值语句替换为以下内容

$ID = & { 
        $_.BaseName -match "(\d.{6})" | Out-Null
        $matches[0] 
    }

答案2

这是另一种方法,它关注文本中的分隔符,而不是长度或字符类。它假定代码后的下划线是文件名中的第一个或唯一一个下划线。:

gci *.rar | ForEach{
   $NewBase = $_.BaseName.Split('_')[0]
   $Code    = $NewBase.Split(' ')[-1] 
   Rename-Item $_.FullName "$NewBase.rar"
   gci *.pdf | ? BaseName -match $Code | Rename-Item -NewName "$NewBase.pdf"
}

逐步文件名解析演示:

PS C:\> $a = 'First Man 11e2345_some text to remove.rar'
PS C:\> $a.Split('_')
First Man 11e2345
some text to remove.rar
PS C:\> $a.Split('_')[0]
First Man 11e2345
PS C:\> $a.Split('_')[0].split(' ')
First
Man
11e2345
PS C:\> $a.Split('_')[0].split(' ')[-1]
11e2345
PS C:\>

参考

获取 ChildItem/gci

ForEach 对象

String.Split 方法

关于数组

重命名项目

哪里-对象/?

PowerShell 学习资源

相关内容