I am moving files from one directory to a newly created directory. Currently the script inserts the id variable to the start of the file name for all the file names.
I would like to insert the id variable after model name variable in all the file names. How do I do that?
I have the following code in my cmd file.
@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"
)
A few small alterations, should get you going.
@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!"
)
tfizhardinge,
Scott C provided the correct answer using cmd.
Here is a Powershell option for you, I've tried to match your cmd code, so you can see what is going on.
# 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 ------