How to replace space in file names

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lalat06bag
Posts: 51
Joined: 10 Jan 2018 15:21

How to replace space in file names

#1 Post by lalat06bag » 14 Feb 2018 12:07

Hi,

I have these files in a folder ab and I want to replace the spaces in the file name to _.

XXXX_acc-er-in.pdf
xxxx_can mess comp-en-us.pdf
dddd_ee_le_ang-er-in.pdf
cccc_Rel File ope-in-er.pdf
xxx_etiti File ope-in-er.pdf

So it would be

XXXX_acc-er-in.pdf
xxxx_can_mess_comp-en-us.pdf
dddd_ee_le_ang-er-in.pdf
cccc_Rel_File_ope-in-er.pdf
xxx_etiti File_ope-in-er.pdf


Need help.
Can anyone please see, what's wrong in this? Ren is showing incorrect syntax.


Set "Pattern= "
Set "Replace=_"
For /f "delims=" %%a in ('dir /b /s %allTxtFiles%\*.txt') Do (
Set "File=%%~a"
echo "!File:%Pattern%=%Replace%!"
echo "%%a"
Ren "%%a" "!File:%Pattern%=%Replace%!"
)

Hackoo
Posts: 103
Joined: 15 Apr 2014 17:59

Re: How to replace space in file names

#2 Post by Hackoo » 14 Feb 2018 14:32

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

Code: Select all

@echo off
Set "Pattern= "
Set "Replace=_"
Setlocal EnableDelayedExpansion
For /f "delims=" %%a in ('dir /b /s "*.txt"') Do (
Set "File=%%~nxa"
echo Ren "%%a" "!File:%Pattern%=%Replace%!"
)
pause

lalat06bag
Posts: 51
Joined: 10 Jan 2018 15:21

Re: How to replace space in file names

#3 Post by lalat06bag » 14 Feb 2018 14:54

Thank you a lot.

Osmium Programming
Posts: 14
Joined: 16 Oct 2017 20:15

Re: How to replace space in file names

#4 Post by Osmium Programming » 16 Feb 2018 19:21

A way to replace those characters in variables is like so:

Code: Select all

set a=%a: =_%
From there you could have a for command rename all those files.

Post Reply