Supermartingale
Supermartingale

Reputation: 115

Removing a prefix with ren command doesn't work

I'm only a beginner at batch programming, so this question might be really simple.

The command is ren -* *; I want to rename all files starting with a dash; for example, -spec.txt to spec.txt.

However it doesn't work! Why?

Upvotes: 0

Views: 237

Answers (2)

Endoro
Endoro

Reputation: 37569

try this (command line, for batch script double the % to %%):

for /f "delims=-" %i in ('dir /b /a-d -*') do if not exist "%i" rename "-%i" "%i"

The code renames the file only if no file with this name already exists to avoid error messages.

Upvotes: 1

dbenham
dbenham

Reputation: 130819

Because that is not how the REN command interprets wildcards ;-)

If you want to know how it works, then have a look at How does the Windows RENAME command interpret wildcards?.

Unfortunately, you cannot use a simple REN command to remove the leading -. You will need to write and use a short batch script instead. Something like the following will do the trick. I toggle delayed expansion on and off to avoid problems with ! in file names.

@echo off
setlocal disableDelayedExpansion
for %%F in (-*) do (
  set "file=%%F"
  setlocal enableDelayedExpansion
  ren "!file!" "!file:~1!"
  endlocal
)

If you know that your file names never contain !, then the script can be as simple as:

@echo off
setlocal enableDelayedExpansion
for %%F in (-*) do (
  set "file=%%F"
  ren "!file!" "!file:~1!"
)

Upvotes: 2

Related Questions