# Solved: Rename End of a filename from batch



## Bismoy (Jan 24, 2013)

Hi everyone, I want to rename a file from command prompt or batch file, for example:

Test_user_240120130953.txt
to
Test_user_24012013.txt

The last 4 digit of the file (0953) needs to be removed and rest remain same.
If someone can help me with the syntax I'll appreciate it.
MAny thanks for your help in advance.


----------



## foxidrive (Oct 20, 2012)

```
@echo off
set file=Test_user_240120130953.txt

for %%a in ("%file%") do (
set "name=%%~na"
set "ext=%%~xa"
)

set "name=%name:~0,-4%"

echo ren "%file%" "%name%%ext%"
```


----------



## Bismoy (Jan 24, 2013)

Hi foxdrive,

Thanks for the answer.
But my text file name will chnage so set file = Test_user_240120130953.txt might not work, if the file name change.
so, what ever the file the last 4 digit needs to be removed.

 foxidrive


----------



## foxidrive (Oct 20, 2012)

You didn't ask to rename a set of files. 

Explain what you want to do, because we can't know exactly what you want to do unless you tell us.


----------



## shirulkar (Jan 24, 2013)

Hi following will work but only for file extension with 3 chararcter like .xls .txt not for .xlsx. for that i need some time

@ECHO OFF
FOR /F "delims=" %%F IN ('DIR /b/o-n/a-d C:\Users\shirulkar\Desktop\mnq\Xyz\Abc\*.*') DO CALL :FileName %%F

EXIT /b

:FileName
SET filename=%~1
SET filename1=%filename:~-4%
SET filename2=%filename:~0,-8%
rename C:\Users\shirulkar\Desktop\mnq\Xyz\Abc\%filename% %filename2%%filename1%

EXIT /b


----------



## foxidrive (Oct 20, 2012)

Your code has issues with long filenames, spaces and & 

The extension can be extracted from %~x1 which will show .xls or .xslx
The name itself is similarly taken from %~n1


----------



## shirulkar (Jan 24, 2013)

Thanks Foxidrive

I think following will work.

FOR /F "tokens=* delims=" %%G IN ('DIR /b /s /a-d C:\Users\shirulkar\Desktop\mnq\Xyz\Abc\*.*') DO call :filename "%%~nG" "%%~xG"

Exit /b

:filename
set "filename=%~1"
set "extn=%~2"
set "filename1=%filename:~0,-4%"
ren "C:\Users\shirulkar\Desktop\mnq\Xyz\Abc\%filename%%extn%" "%filename1%%extn%"

exit /b


----------



## Bismoy (Jan 24, 2013)

Thanks all the solution has helped.


----------

