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

+3


source to share


2 answers


This should do it.



@echo off
setlocal EnableDelayedExpansion
for %%x in ("C:\Users\user\Documents\monthly_adhoc\importclm\*.dbf") do (
  set newname=%%~nx
  ren "%%x" "!newname:~0,8!.dbf"
)

      

+2


source


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.

+2


source







All Articles