CMD: Script to batch rename files in a folder based on the first 8 characters of its name
I am trying to rename dbf files to a folder. The script package below is currently configured to rename the file to its current name. How can I change the syntax to rename files with only the first 8 characters, including the .dbf extension? I've tried using "%% ~ nx: ~ 8.dbf" for the recipient name, but it doesn't seem to work. Thank!
for %%x in ("C:\Users\user\Documents\monthly_adhoc\importclm\*.dbf") do (
rename "%%x" "%%~nx.dbf")
The input files will be something like this:
12345678_XXXXXXX_KKKKKK.dbf
12364178_XXXXXXX_KKKKKK.dbf
12124668_XXXXXXX_KKKKKK.dbf
12342178_XXXXXXX_KKKKKK.dbf
Id want the output files to be like this.
12345678.dbf
12364178.dbf
12124668.dbf
12342178.dbf
source to share
You need an intermediate variable ( FileName
) to extract the first 8 characters of each filename:
setlocal EnableDelayedExpansion
for %%X in ("C:\Users\user\Documents\monthly_adhoc\importclm\*.dbf") do (
set FileName=%%~nX
rename "%%~X" "!FileName:~0,8!%%~xX")
endlocal
Block setlocal
/ endlocal
provides slow expansion. Take a look at this post for an explanation.
source to share