3

I am trying to rename dbf files in a folder. The batch script below is currently set up to rename the file to its current name. How do I modify the syntax to rename the files with just the first 8 characters, including the .dbf extension? I’ve tried using “%%~nx:~8.dbf” for the destination name, but it doesn’t seem to work. Thank you!

for %%x in ("C:\Users\user\Documents\monthly_adhoc\importclm\*.dbf") do (
rename "%%x" "%%~nx.dbf")

The input files would be something like this:

12345678_XXXXXXX_KKKKKK.dbf

12364178_XXXXXXX_KKKKKK.dbf

12124668_XXXXXXX_KKKKKK.dbf

12342178_XXXXXXX_KKKKKK.dbf

I’d want the output files to be this.

12345678.dbf

12364178.dbf

12124668.dbf

12342178.dbf

Snoobie
  • 193
  • 1
  • 4
  • 14
  • 1
    If you can re-use [this answer](http://stackoverflow.com/a/27604839/3959875) and split at `_` then this question can be closed as a duplicate. – wOxxOm Jul 30 '15 at 21:54

2 Answers2

2

You need an interim variable (FileName) for extracting 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

The setlocal/endlocal block enables delayed expansion. Take a look at this post for an explanation.

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99
2

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"
)
UnknownOctopus
  • 2,057
  • 1
  • 15
  • 26