powershell - Powershell根据前缀为文件名添加后缀
问题描述
我有一个目录,其中包含许多已命名的文本文件:
1Customer.txt
2Customer.txt
...
99Customer.txt
我正在尝试创建将文件重命名为更合乎逻辑的 powershell 脚本:
Customer1.txt
Customer2.txt
...
Customer99.txt
前缀可以是 1 位到 3 位之间的任何值。
由于我是 powershell 新手,我真的不知道如何实现这一点。非常感谢任何帮助。
解决方案
这是一种方法:
Get-ChildItem .\Docs -File |
ForEach-Object {
if($_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
{
Rename-Item -Path $_.FullName -NewName "$($matches.Type)$($matches.Number)$($_.Extension)"
}
}
该行:
$_.Name -match "^(?<Number>\d+)(?<Type>\w+)\.\w+$")
获取文件名(例如“23Suppliers.txt”)并对其执行模式匹配,提取数字部分(23)和“类型”部分(“供应商”),分别命名为“数字”和“类型” . 这些由 PowerShell 存储在其自动变量中$matches
,该变量在使用正则表达式时使用。
然后,我们使用原始文件的详细信息重建新文件,例如文件的扩展名 ( $_.Extension
) 和匹配的类型 ( $matches.Type
) 和编号 ( $matches.Number
):
"$($matches.Type)$($matches.Number)$($_.Extension)"
推荐阅读
- laravel - 删除laravel中的所有存储文件
- assembly - 当我尝试 DIV 时,我得到“除以零”但它不是零
- string - 如何在kotlin中从旧字符串创建新字符串
- java - 使用上下文路径的 POST 调用在 Spring Boot 2.x 中不起作用
- c - 客户端读取的字节数多于在 C 中发送的字节数 - linux
- c++ - 如何从其他线程中断 std::cin(std::cin.getline) 执行
- git - vs代码在打开核心编辑器后不会停止在 git rebase -i 中间步骤
- python - 使用 pip 安装 PyTorch 时出错 - 无法构建轮子
- azure - 如何更改 Windows 容器的 webapp 服务中的时区
- python-xarray - 在 xarray.Dataset 上调用 .metpy.parse_cf() 会给出未定义的“ctables”