我正在尝试使用每个文件的第一行批量重命名纯文本文件。我只想保留字母数字字符,在你的帮助下我就快到了。唯一的问题是我需要像 é
这样的重音字符或á
以各自的非重音字符的形式保留:e 和 a(文本为西类牙语)或按原样保留在名称中,而不是删除。这是我现在正在使用的:
Get-ChildItem *.txt | Rename-Item -NewName {
$firstLine = ($_ | Get-Content -TotalCount 1) -replace '[^a-z0-9 ]'
'{0}.txt' -f $firstLine
}
谢谢。如果可能的话,请告诉我是否有办法保留符号“?”也是。
最佳答案
方法类似于 this answer 中使用的方法,您可以使用String.Normalize
Method在替换正则表达式之前。
至于不删除?
,您可以简单地将其添加到字符范围:[^a-z0-9 ?]
,但它是无效字符Windows 中的文件名,因此未在此答案的重命名代码片段中使用。您可以使用[IO.Path]::GetInvalidFileNameChars()
获取您操作系统的无效字符列表。
Get-ChildItem *.txt | Rename-Item -NewName {
$firstLine = ($_ | Get-Content -TotalCount 1 -Encoding utf8).
Normalize([Text.NormalizationForm]::FormD) -replace '[^a-z0-9 ]'
'{0}.txt' -f $firstLine
}
示例:
$string = 'áÁéÉñÑ?'
$string.Normalize([Text.NormalizationForm]::FormD) -replace '[^a-z0-9 ?]'
# Outputs:
# aAeEnN?
值得注意,默认Get-Content
encoding在 Windows PowerShell 中将会出现问题:
Default
Uses the encoding that corresponds to the system's active code page (usually ANSI).
因此需要-Encoding utf8
。较新的 PowerShell 版本不存在此类问题,因为它们默认为 utf8NoBOM
。
关于powershell - 如何在 Powershell 中使用第一行重命名文本文件时替换重音字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75892416/