使用Windows REN将文本插入文件名,并保留名称的其余部分



我目前正在尝试使用REN命令在文件名中间添加文本,同时保留文件名的其余部分。

示例:

testfile_2018-11-14-06-06-23.pdf->testfile_ABCD_2018-11-14-06-06-23.pdf

最后六位数字可能会更改,所以我需要用通配符来表示它们。

目前,我有以下几种:

REN testfile_2018-11-14*.pdf testfile_ABCD_2018-11-14*.pdf

结果是:testfile_ABCD_2018-11-146-23.pdf

最后六位数字没有被保留,我不明白为什么。

很确定这不能用简单的REN命令完成。但是,您可以使用FOR /F命令的强大功能来操作文件名。

可以在命令提示符下运行此操作。

for /f "tokens=1* delims=_" %G IN ('dir /a-d /b "testfile_2018-11-14*.pdf"') do ren "%G_%H" "%G_ABCD_%H"

这会找到文件,然后用下划线分隔文件名。然后,它使用新文件名中的额外字符串对其进行重命名。

如果要在批处理文件中运行此操作,则必须将百分比符号增加一倍。

如果我们为REN提供替代解决方案,PowerShell中有以下几种方法:

字符串拆分:

## Get a System.IO.FileInfo object to the file
$f = Get-Item path-to-the-testfile
## Split up the name by the underscore so the zeroth entry is 'testfile' and the first entry is the remaining name
$s = $f.Name.Split("_")
## Use String tokenization to recombine the different parts in the desired order during the rename
Rename-Item $f.FullName ("{0}{1}_{2}_{3}" -f $f.DirectoryName, $s[0], 'ABCD', $s[1])

字符串替换:

## Get a System.IO.FileInfo object to the file
$f = Get-Item path-to-the-testfile
## Use string replace to fix the name during the rename operation
Rename-Item $f.FullName ($f.FullName.Replace('testfile_', 'testfile_ABCD_'))

使用regex是可能的,但如果您不熟悉上面的方法,可能会过于复杂。

最新更新