Solved How to get rid of exclamation in filename using batch file?

June 26, 2013 at 17:13:25
Specs: Windows 7
I know how to replace words in a filename using a batch code but removing exclamations doesn't work. Here what I use to remove other characters.

echo off
SETLOCAL EnableDelayedExpansion
FOR /f "tokens=*" %%a IN ('DIR /b "*.flv"') DO (
SET Var=%%~na
SET Var=!Var:a=_!
REN "%%a" "!Var!.flv"
)

The above code will replace any .flv filename containing the letter "a" with a _, but I need a code that would replace ! with an _. I can't substitue ! in place of the letter "a" because the code itself uses an !. . Any help is appreciated. Thanks.


See More: How to get rid of exclamation in filename using batch file?

Report •


✔ Best Answer
August 12, 2013 at 08:09:42
As nbrane said his method doesn't work with file names with more than one !, here is a method that does. It uses a sneaky trick to implement delayed expansion without using the ! character, and without using the EnableDelayedExpansion option.

@echo off
setlocal DisableDelayedExpansion

FOR %%a IN (*.flv) DO (
SET Var=%%~na
CALL SET Var=%%Var:!=_%%
CALL REN "%%a" "%%Var%%.flv"
)

message edited by klint



#1
June 26, 2013 at 17:37:02
What if you put the ! in quotes "!"

How do you know when a politician is lying? His mouth is moving.


Report •

#2
June 27, 2013 at 19:14:18
@guapo: right idea, just needs a boost:

There are various ways, but maybe the easiest (and therefore, according to Occam, best) method is like this:

@echo off & setlocal enabledelayedexpansion
for /f "tokens=1,2 delims=!" %%a in ('dir /b *.flv') do (
echo ren "%%a^!"%%b %%a_%%b
)

other methods involve disabling delayedexpansion, but that gets messy, imo. This will of course fail (as written) if more than one "!" is in the filename-path.

Report •

#3
June 29, 2013 at 03:59:03
nbrane,

That's pretty slick, Slick.

=====================
M2 Golden-Triangle


Report •

Related Solutions

#4
August 12, 2013 at 08:09:42
✔ Best Answer
As nbrane said his method doesn't work with file names with more than one !, here is a method that does. It uses a sneaky trick to implement delayed expansion without using the ! character, and without using the EnableDelayedExpansion option.

@echo off
setlocal DisableDelayedExpansion

FOR %%a IN (*.flv) DO (
SET Var=%%~na
CALL SET Var=%%Var:!=_%%
CALL REN "%%a" "%%Var%%.flv"
)

message edited by klint


Report •

#5
August 13, 2013 at 02:53:29
hi klint,

You got me mystified.

=====================
M2 Golden-Triangle


Report •

#6
August 13, 2013 at 09:30:19
It's a quirk of CMD's command parsing, caused by the CALL command forcing another round of parsing. The "%%" are parsed to just "%" during the first pass, and that leads to a valid variable name. The now valid variable is expanded while executing the CALL statement.
http://www.computing.net/howtos/sho...

How To Ask Questions The Smart Way

message edited by Razor2.3


Report •


Ask Question