关于按照解决方案使用 Powershell 重命名文件和文件内内容的问题here https://stackoverflow.com/questions/77081055/renaming-of-files-and-content-within-files-using-powershell.
使用下面的脚本,所有文件名和文件中出现的位置都会被重命名。
替换不区分大小写,即无论是否出现“uvw”、“UVW”、“Uvw”等,替换都是“XYZ”。
是否可以尊重原文的情况,重新命名为“true to origin”,即
“uvw”->“xyz”,“UVW”->“XYZ”,“Uvw”->“Xyz”(默认情况下“abc_123”应该是“def_123”而不是“DEF_123”)?
$filePath = "C:\root_folder"
$include = '*.txt', '*.xml' # adapt as needed
Get-ChildItem -File $filePath -Recurse -Include $include |
Rename-Item -WhatIf -PassThru -NewName { $_.Name -replace 'UVW', 'XYZ' } |
ForEach-Object {
($_ | Get-Content -Raw) -replace 'ABC_123', 'DEF_123' |
Set-Content -NoNewLine -LiteralPath $_.FullName
}
另一种方法圣地亚哥的有用答案 https://stackoverflow.com/a/77089648/45375,它也依赖于为每个匹配调用的匹配评估器脚本块:
总体思路是:
- 循环匹配匹配文本和替换文本共享的字符数
- Use a System.Text.StringBuilder https://learn.microsoft.com/en-US/dotnet/api/System.Text.StringBuilder实例来逐个字符地构建替换文本的大小写匹配版本。
- 替换字符串中的任何其他字符(匹配文本中没有对应字符的字符)将按原样保留。
两种解决方案均低于输出<XyZ>
, 如预期。
PowerShell(核心)7+ https://github.com/PowerShell/PowerShell/blob/master/README.md解决方案:
# Sample input string
$inputString = '<UvW>'
# Sample search pattern.
$searchPattern = 'uvw'
# Sample replacement text.
$replaceWith = 'xyz'
# A string builder to make constructing the case-matched replacement string
# more efficient.
$caseMatchedReplaceWith = [System.Text.StringBuilder]::new($replaceWith.Length)
$inputString -replace $searchPattern, {
$matchedText = $_.Value
$numCharsToMatch = [Math]::Min($replaceWith.Length, $matchedText.Length)
$null = $caseMatchedReplaceWith.Clear()
foreach ($i in 0..($numCharsToMatch-1)) {
$replacementChar = $replaceWith[$i]
if ([char]::IsUpper($matchedText[$i]) -and -not [char]::IsUpper($replacementChar)) {
$replacementChar = [char]::ToUpper($replacementChar)
}
$null = $caseMatchedReplaceWith.Append($replacementChar)
}
$caseMatchedReplaceWith.ToString() + $replaceWith.Substring($numCharsToMatch)
}
Windows PowerShell解决方案(其中使用脚本块作为替换操作数-replace
不支持):
# Sample input string
$inputString = '<UvW>'
# Sample search pattern.
$searchPattern = 'uvw'
# Sample replacement text.
$replaceWith = 'xyz'
# A string builder to make constructing the case-matched replacement string
# more efficient.
$caseMatchedReplaceWith = [System.Text.StringBuilder]::new($replaceWith.Length)
[regex]::Replace(
$inputString,
$searchPattern,
{
$matchedText = $args[0].Value
$numCharsToMatch = [Math]::Min($replaceWith.Length, $matchedText.Length)
$null = $caseMatchedReplaceWith.Clear()
foreach ($i in 0..($numCharsToMatch-1)) {
$replacementChar = $replaceWith[$i]
if ([char]::IsUpper($matchedText[$i]) -and -not [char]::IsUpper($replacementChar)) {
$replacementChar = [char]::ToUpper($replacementChar)
}
$null = $caseMatchedReplaceWith.Append($replacementChar)
}
$caseMatchedReplaceWith.ToString() + $replaceWith.Substring($numCharsToMatch)
},
'IgnoreCase'
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)