• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 824
  • Last Modified:

Batch file to add a file extension to all files in a directory without one

Greetings,

I have a directory on a Windows XP machine that contains hundreds of files that look like this:

ABC
ABC.idx
DEF
DEF.idx
GHI
GHI.idx
JKL
JKL.idx

Some of them have valid file extensions and some have no file extensions.  

I'd like to write a batch file that adds a .DAT file extension to all files in my directory with no extension and leave the files with an extension unchanged.

I tried this at the command line:

for %x in (*) do ren "%x" "%x.DAT"

and got this:
ABC.DAT
ABC.idx.DAT

Can I do this with a batch file? If so, suggestions please.

Many thanks!
0
monkeybiz12345
Asked:
monkeybiz12345
1 Solution
 
QlemoC++ DeveloperCommented:
It's much easier than you would expect:
  ren *. *.dat
will only rename files without extension. However, if you execute that twice, you will get an (stupid) error message - "The syntax of the command is incorrect.". Just ignore that, it is trying to tell you that there are no files to rename.
0
 
paultomasiCommented:
Qlemo

Nice one. To suppress the error messege, it would be better to do it like this:

    ren *. *.DAT 2>nul



monkeybiz12345

Please try this:

    @for %a in (*.*) do @if "%~xa"=="" @ren "%a" "%a.dat"

The '@' symbols just suppress the echoing of commands to the screen and aren't strictly needed.



In a batch file you would do it like this:

@echo off
for %%a in (*.*) do if "%%~xa"=="" ren "%%a" "%%a.dat"

Open in new window

0
 
monkeybiz12345Author Commented:
ZOINKS!  Why didn't I think of that?  

Qlemo, that's exactly what I needed.
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now