PowerShell 正则表达式批量替换文件名 [英] PowerShell Regex Bulk Replace Filenames

查看:82
本文介绍了PowerShell 正则表达式批量替换文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换给定文件夹中的文件名,但在 PowerShell 中使用正则表达式作为过滤器和新文件名.

I am trying to replace filenames in a given folder, but using regular expressions as a filter and in the new filenames, in PowerShell.

例如,文件名CEX-13"应重命名为C-0013";CEX-14"应改为C-0014"等

For example, a file name "CEX-13" should be renamed to "C-0013"; "CEX-14" should change to "C-0014", etc.

我有这个,但是我收到一个错误,说我无法创建一个已经存在的文件.

I have this, but I get an error that I cannot create a file that already exists.

我当前的代码是:

foreach ($file in get-childitem | where-object {$_.name -match "^CEX-(\d\d)"})
{
    rename-item $file -newname ($file.name -replace "^CEX-(\d\d)", "C-00$1")
}

任何帮助将不胜感激.

推荐答案

您需要在替换中使用美元来绕过字符串中的 PowerShell 变量扩展,并在它到达正则表达式引擎时保持美元符号.

You need the dollar in the replacement to get past the PowerShell variable expansion in strings, and stay as a dollar sign as it gets to the regex engine.

>

当前 "C-00$1" 变成了 "C-00" 并且所有文件都将获得相同的名称.

Currently "C-00$1" becomes "C-00" and all the files will get the same name.

你需要用反引号将它转义

You need to escape it with a backtick

"C-00`$1"

或使用单引号'C-00$1'

这篇关于PowerShell 正则表达式批量替换文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆