Xander Vane
Xander Vane

Reputation: 197

Remove Last Characters from my filenames in windows

Im quite new to batch programming and i wanted to remove the last characters on my filename.

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

I want to remove the last 4 digits on my filename how i could do that?

I have tried this

@echo off
setlocal enabledelayedexpansion
set X=3
set FOLDER_PATH=
pushd %FOLDER_PATH%
for %%f in (*) do if %%f neq %~nx0 (
    set "filename=%%~nf"
    ren "%%f" "!filename!%%~xf"
)
popd
PAUSE

but it removes on first and last characters, i only saw this here too, im still quite confused how this works

Upvotes: 3

Views: 36981

Answers (3)

TheWebExpert
TheWebExpert

Reputation: 9

Thank you SO much to DIMM_V2; the file is now as follows:

::working script to rename + remove suffix
::fixed problem file is not found while rename.
@echo off
set /a count = 0
for %%i in ("*_removed.PDF") do (set fname=%%i) & call :rename
goto :eof
:rename
::template name ==> name_removed.PDF
::to rename the begin  change zero to something
set name=%fname:~0,-12%
set /a count=count+1
::by random or count i bypass the problem of file not found while rename
ren "%fname%" "%name%.PDF"

This worked PERFECTLY. The file gets renamed just as I wanted. It was pretty simple to just highlight the file, press F2, and rename it - but it was a pain in the butt, as I'm having to do this fairly frequently. This batch file has made my life much, MUCH easier! Thanks again!

Upvotes: 0

DIMM_V2
DIMM_V2

Reputation: 131

::working script to rename + remove suffix
::fixed problem file is not found while rename.
@echo off
set /a count = 0
for %%i in ("*.ts") do (set fname=%%i) & call :rename
goto :eof
:rename
::template name ==>   names__1xxx.ts
::to rename the begin  change zero to something
set name=%fname:~0,-8%
set /a count=count+1
::by random or count i bypass the problem of file not found while rename
ren "%fname%" "%name%_%count%.ts`

Results :

before : names__1xxx.ts

after : names__1.ts

Upvotes: 0

unclemeat
unclemeat

Reputation: 5207

With your recent clarification - I would do the following.

@echo off
setlocal enabledelayedexpansion
set FOLDER_PATH=C:\Some\Path\
for %%f in (%FOLDER_PATH%*) do if %%f neq %~nx0 (
    set "filename=%%~nf"
    ren "%%f" "!filename:~0,-4!%%~xf"
)
PAUSE

This will change your examples

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

Into

10_myfile_12345_.txt
11_myfile_12345_.txt

If you want to remove the trailing _ simply change !filename:~0,-4! to !filename:~0,-5!. This is simple string manipulation.

Upvotes: 8

Related Questions