[英]Using Windows REN to insert text into a filename, maintaining the rest of the name?
I'm currently trying to use the REN command to add text in the middle of a filename, while maintaining the rest of the filename. 我目前正在尝试使用REN命令在文件名中间添加文本,同时保留其余文件名。
Example: 例:
testfile_2018-11-14-06-06-23.pdf
-> testfile_ABCD_2018-11-14-06-06-23.pdf
testfile_2018-11-14-06-06-23.pdf
> testfile_ABCD_2018-11-14-06-06-23.pdf
The last six digits are subject to change, so I need to represent them with wildcards. 后六位数字可能会发生变化,因此我需要用通配符表示它们。
Currently, I have the following: 目前,我有以下内容:
REN testfile_2018-11-14*.pdf testfile_ABCD_2018-11-14*.pdf
Result is: testfile_ABCD_2018-11-146-23.pdf
结果是:
testfile_ABCD_2018-11-146-23.pdf
The last six digits are not being maintained, and I cannot figure out why. 最后六位数字未保留,我不知道为什么。
Pretty sure it cannot be done with a simple REN
command. 可以肯定的是,用一个简单的
REN
命令不能完成它。 You can however use the power of the FOR /F
command to manipulate the file name. 但是,您可以使用
FOR /F
命令的功能来操纵文件名。
From the command prompt you can run this. 在命令提示符下,您可以运行此命令。
for /f "tokens=1* delims=_" %G IN ('dir /a-d /b "testfile_2018-11-14*.pdf"') do ren "%G_%H" "%G_ABCD_%H"
This finds the file and then splits the file name by the underscore. 这将找到文件,然后用下划线分隔文件名。 It then renames it with the extra string in the new file name.
然后,使用新文件名中的额外字符串将其重命名。
If you are going to run this in a batch file you must double the percent symbols. 如果要在批处理文件中运行此程序,则必须将百分比符号加倍。
If we're offering alternative solutions to REN, here are a few ways in PowerShell: 如果我们为REN提供替代解决方案,则在PowerShell中有以下几种方法:
String Splitting: 字符串分割:
## 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])
String Replace: 字符串替换:
## 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_'))
Using regex is possible but is probably overly complicated if you're not familiar with the above methods. 可以使用正则表达式,但是如果您不熟悉上述方法,可能会过于复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.