Reputation: 25
I need to change a file name in a batch script.
Below is a sample I made
SET date = 20210803
SET job = 69187
cd "H:\arbortray foldher\"
for %%i in (*.txt*) do REN %%i randum_%job%-text-%date%%%i
It is not working; does nothing. I want it to change a specific file name from a generic version to one using the globally defined variables that are used through out the script. The file is already being moved from another program that makes the file into this folder. I can not include the variable in the file name at those steps. I want to include the commands as part of a larger script that does other things using the variables. Specifically, in this case I need the commands to rename the file from the generic version to one that includes variables defined earlier in the script. These variables change weekly.
Upvotes: 1
Views: 9796
Reputation: 26
your example insecure:
insecure?
%answer:
@echo off
chcp 65001 >NUL 2>NUL.
set "v_date=20210803"
set "v_job=69187"
set "v_dir=%cd%"
for /f "tokens=* delims=" %%s in ('dir /b /a-d "%v_dir%" ^| findstr /i /e /c:".txt"') do @ren "%v_dir%\%%s" "randum_%v_job%-text-%v_date%%%s"
forgot about /d
and cd
))
maybay you mean "randum_69187-text-20210803-
example.txt" in example
result?
Upvotes: 0
Reputation: 41267
The problems are:
A) Your variable names will have spaces in them.
B) The CD command needs a /d
C) The for in do has a bug which has to be worked around by changing the extension and restoring it later.
@echo off
SET date=20210803
SET job=69187
cd /d "H:\arbortray foldher\"
for %%i in (*.txt) do REN "%%i" "randum_%job%-text-%date%%%~ni.tmp"
ren *.tmp *.txt
echo done
pause
The spaces caused the issue and in the rename command you need double quotes to cater for spaces.
Upvotes: 0