我正在将文件从一个目录移动到新创建的目录。目前,该脚本将id变量插入到所有文件名的文件名的开头。 我想在所有文件名中的模型名称变量之后插入id变量。我该怎么做?
我的cmd文件中有以下代码。
@echo off
rem set 12d variables
set modelname=dr network_
set id=10yr_
mkdir "%modelname%"
rem move to new dir created
move "%modelname%*.rpt" "%modelname%"
rem change working directory
cd "%modelname%"
rem for each file rename it and add the new prefix %id% to the file name
for %%f in ("%modelname%*.rpt") do (
rename "%%f" "%id%%%f"
)
答案 0 :(得分:0)
一些小的改动,应该让你去。
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
rem set 12d variables
set modelname=dr network_
set id=10yr_
mkdir "%modelname%"
rem move to new dir created
move "%modelname%*.rpt" "%modelname%"
rem change working directory
cd "%modelname%"
rem Work out how long the modelname is
echo %modelname%>strlen.txt
for %%a in (strlen.txt) do set /a modelNameLength=%%~za - 2
del strlen.txt
rem for each file rename it and add the new text %id% to the middle of the file name
for %%f in ("%modelname%*.rpt") do (
set newfilename=%%f
set newfilename=!newfilename:~0,%modelNameLength%!%id%!newfilename:~%modelNameLength%!
ren "%%f" "!newfilename!"
)
答案 1 :(得分:0)
tfizhardinge, Scott C使用cmd提供了正确的答案。
这是一个Powershell选项,我尝试匹配您的cmd代码,以便您可以看到发生了什么。
# Rename using replace to insert text in the middle of the name
# Set directory where the files you want to rename reside
# This will allow you to run the script from outside the source directory
Set-Variable -Name sourcedir -Value "c:\test"
# Set folder and rename variables
Set-Variable -Name modelname -Value "dr network_"
Set-Variable -Name id -Value "10yr_"
# Set new filename which is modelname string + id variable
Set-Variable -Name newmodelname -Value $modelname$id
# Check if folder exisits, if not create
if(!(Test-Path -Path $sourcedir\$modelname )){
# rem make directoy with modelname variable
New-Item -ItemType directory -Path $sourcedir\$modelname
}
# Move the rpt files to new dir created
Move-Item -Path $sourcedir\*.rpt -Destination $sourcedir\$modelname
# Using GetChildItem (i.e. Dir in dos) command with the pipe, will send a list of files to the Rename-Item command
# The Rename-Item command is replacing the modelname string with new modelname string defined at the start
Get-ChildItem -Path $sourcedir\$modelname | Rename-Item -NewName { $_.name -replace $modelname, $newmodelname }
# You can remove the stuff below this line -----
# Pause here so you can check the result.
# List renamed files in their new directory
Get-ChildItem -Path $sourcedir\$modelname
# rem Pause
Write-Host "Press any key"
$pause = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# rem End ------