HyeVltg3
HyeVltg3

Reputation: 11

Replace Spaces and . in filename with Underscores

I followed https://stackoverflow.com/a/16129486/2000557 's example and modified the script for a folder of video files.

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=."
Set "Replace=_"

For %%a in (*.avi) Do (
Set "File=%%~a"
Ren "%%a" "!File:%Pattern%=%Replace%!"
)

For %%a in (*.mkv) Do (
Set "File=%%~a"
Ren "%%a" "!File:%Pattern%=%Replace%!"
)

For %%a in (*.mp4) Do (
Set "File=%%~a"
Ren "%%a" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

Can anyone explain why this also replaces the last dot in the filename (that is a part of the extension) into an underscore. this feels like I was given the fish and not taught how to fish. this script works, but sadly it replaces the last period also.
I'd like to use the script without having to turn on Hide Extensions.

Upvotes: 1

Views: 2516

Answers (2)

Hackoo
Hackoo

Reputation: 18827

You can try with this batch script :

@echo off
Setlocal enabledelayedexpansion
Set "FileType=avi mp4 mkv"
Call :Search_Replace " " "." "!FileType!"
Call :Search_Replace "." "_" "!FileType!"
Timeout -1 & exit
::********************************************************
:Search_Replace <Pattern> <Replace> <FileType>
Set "Pattern=%~1"
Set "Replace=%~2"
@For %%# in (%~3) do (
    For %%a in (*.%%#) Do (
        Set "File=%%~na"
            ren "%%a" "!File:%Pattern%=%Replace%!%%~xa"
    )
)
Exit /b
::********************************************************

Upvotes: 0

user6811411
user6811411

Reputation:

The substitution is overall and can't be limited.

The workaround is easy just use the name without extension for file and append the original extension - this way only one for (for each substitution) is needed.

@echo off & Setlocal EnableDelayedExpansion
For %%A in ("*.*.avi" "*.*.mkv" "*.*.mp4") Do (
    Set "File=%%~nA"
    Ren "%%A" "!File:.=_!%%~xA" 2>NUL
)

For %%A in ("* *.avi" "* *.mkv" "* *.mp4") Do (
    Set "File=%%~nA"
    Ren "%%A" "!File: =_!%%~xA" 2>NUL
)

Or this version

For %%A in (*.avi *.mkv *.mp4) Do (
    Set "File=%%~nA"
    Set "File=!File: =_!"
    Set "File=!File:.=_!"
    If "%%~nA" neq "!File!" Ren "%%A" "!File!%%~xA"
)

I'm not shure which is more efficient.

Upvotes: 2

Related Questions