m2gris
m2gris

Reputation: 21

Renaming multiple files of varying lengths to last 16 characters

I have the following documents in a folder

How do I rename them to include only the last 11 characters?

123_abcdefghijk.doc to abcdefghijk.doc
1234_abcdefghikh.doc to abcdefghikh.doc
12345_abcdefghijl.doc to abcdefghijl.doc

Thanks in advance for your help.

Upvotes: 2

Views: 55

Answers (3)

Leptonator
Leptonator

Reputation: 3499

Like @npocmaka's solution.. However..

Where you have:

echo ren "%%~f#" "%%~dp#!docname!.doc"

You need to check/re-check:

if not exist "%%~dp#!docname!.doc" ( ren "%%~f#" "%%~dp#!docname!.doc"
) else ( echo "%%~dp#!docname!.doc" already exists >> error_log.out )

Upvotes: 0

Magoo
Magoo

Reputation: 79982

for /f "tokens=1*delims=_" %%a in (*_*.doc) do ECHO(ren "%%a_%%b" "%%b"

(as a batch line - from the prompt reduce %% to %)

Assumed that you want to perform the task in the current directory.

Assumed that you actually want to delete the leading string up to and including the _ from the filename.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

Not tested

@echo off

set "doc_dir=c:\docs"

setlocal enableDelayedExpansion

pushd "%doc_dir%"

for %%# in (*.doc) do (
    set "docname=%%~n#"
    set "docname=!docname:~-11!"
    rem !!! remove the echo if ren command looks ok !!!!
    echo ren "%%~f#" "%%~dp#!docname!.doc"
)

endlocal

Upvotes: 1

Related Questions