替换文件名中的第一个字符

时间:2015-12-15 16:37:28

标签: regex powershell

我正在阅读文件名,如果文件不以N开头,我需要用字母N替换该字母。

foreach ($item in Get-ChildItem $Path) {
  Write-host "working on $item"
  if ($item -match "^(N\d{3})") {
    # This file will already process correctly
  } elseif ($item -match "^(\d{3})") {
    $FilePath = $Path + $item
    Write-Host $FilePath

    #Rename this file so it will process correctly
    Rename-Item $FilePath N$item -Force
    Write-Host "Renaming: "$item "to N$item"
  } elseif ($item -match "^[a-zA-Z](\d{3})") {
    #replace first character with "N"
    # How do I replace the first letter with an "N"?
  }
}

1 个答案:

答案 0 :(得分:3)

你觉得太复杂了。这应该足够了:

Get-ChildItem $Path | Rename-Item -NewName { $_.Name -creplace '^[^N]','N' }

或者,如果您不希望那些“已重命名”的文件已经以大写N开头:

Get-ChildItem $Path |
  Where-Object { $_.Name -cmatch '^[^N]' } |
  Rename-Item -NewName { $_.Name -creplace '^[^N]','N' }