# Batch to rename first part of files in a folder...



## billiehawkins (May 5, 2010)

I would like to rename the first part of each file while keeping the rest intact, using a DOS BATCH file if possible.

On the site, there are others posting something similar, but the problem I am running into is because of the [space] in the filename, and that the filename isn't always the same number of chars.

Examples: 
Rename "C:\test\File Name XYZ_123456.txt" to "C:\test\NewFileName_123456.txt" 
Rename "C:\test\File Name XYZ_123456789.txt" to "C:\test\NewFileName_123456789.txt" 
Rename "C:\test\File Name XYZ_001122334455.txt" to "C:\test\NewFileName_001122334455.txt" 
Rename "C:\test\File Name XYZ_123456abc.txt" to "C:\test\NewFileName_123456abc.txt"

As you can see, I just need to change the part "File Name XYZ" to "NewFileName"

the DOS command for rename (REN) seems to dislike the spacing. 
When I try: REN File?Name?XYZ_*.txt NewFileName_*.txt

I get: 
Original File of "File Name XYZ_123456.txt" renamed to "NewFileName_Z_123456.txt"

This leads me to think that REN uses positioning.

(note the space - that's the problem I seem to have)

Any Help would be greatly appreciated!


----------



## Squashman (Apr 4, 2003)

Assuming you always want to rename everything before the underscore this will work.


```
@Echo Off & SetLocal EnableExtensions
For /F "tokens=1* delims=_" %%I IN ('dir /a-d /b *.txt') DO rename "%%~I_%%~J" "NewfileName_%%~J"
```
Output:

```
C:\batch>dir /a-d /b *.txt
File Name XYZ_001122334455.txt.txt
File Name XYZ_123456.txt.txt
File Name XYZ_123456abc.txt.txt

C:\batch>renaming.bat

C:\batch>dir /a-d /b *.txt
NewfileName_001122334455.txt.txt
NewfileName_123456.txt.txt
NewfileName_123456abc.txt.txt

C:\batch>
```


----------



## billiehawkins (May 5, 2010)

Squashman: Thank you so much, I will give it a try!


----------

