使用Windows REN在文件名中插入文本,保留名称的其余部分? 我现在尝试使用RUN命令在文件名中间添加文本,同时维护文件名的剩余部分。
例如:使用Windows REN在文件名中插入文本,保留名称的其余部分? 我现在尝试使用RUN命令在文件名中间添加文本,同时维护文件名的剩余部分。,windows,batch-file,cmd,rename,Windows,Batch File,Cmd,Rename,例如: testfile\u 2018-11-14-06-06-23.pdf->testfile\u ABCD\u 2018-11-14-06-06-23.pdf 最后六位数字可能会更改,因此我需要用通配符表示它们 目前,我有以下几点: REN testfile\u 2018-11-14*.pdf testfile\u ABCD\u 2018-11-14*.pdf 结果是: testfile\u ABCD\u 2018-11-146-23.pdf 最后六位数字没有被维护,我也不知道为什么。很确定
testfile\u 2018-11-14-06-06-23.pdf
->testfile\u ABCD\u 2018-11-14-06-06-23.pdf
最后六位数字可能会更改,因此我需要用通配符表示它们
目前,我有以下几点:
REN testfile\u 2018-11-14*.pdf testfile\u ABCD\u 2018-11-14*.pdf
结果是:
testfile\u ABCD\u 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_'))
使用正则表达式是可能的,但如果您不熟悉上述方法,可能会过于复杂。带字符串拆分的PowerShell或正则表达式非常适合解决此问题。你不使用它的原因是什么?正如@Squashman在他的回答中所说的,单靠REN是无法做到的。请参阅超级用户网站,以获得关于什么可以做和什么不能做的解释。@dbenham,回答如何。我知道这项任务有点过分,但这将是一个有用的答案。