Link to home
Start Free TrialLog in
Avatar of ReneGe
ReneGeFlag for Canada

asked on

Batch File: String manipulation

Hi there,

I want to remove the following caracters from a variable \ : | < > & ^ " ! /.

Thanks for fixing my script,
Rene



@ECHO OFF

SETLOCAL enabledelayedexpansion

SET Title=T\h:i|s< >i&s ^a t"e!s/t:
SET Var=\,:,|,<,>,&,^,",!,/

FOR %%A IN (%Var%) DO SET Title=!Title:%%A=!

ECHO %Title%
PAUSE
EXIT

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oops. Line 12 is not needed and is a stray debugging line.
Avatar of ReneGe

ASKER

Thanks a million Tommy

Cheers,
Rene
Avatar of Bill Prew
Bill Prew

FWIW, this will also work:

SET Title=T\h:i^|s^< ^>i^&s ^^a t"e^!\s/t:
Set "Title=%Title:!=%"
Set "Title=%Title:|=%"
Set "Title=%Title:>=%"
Set "Title=%Title:<=%"
Set "Title=%Title:&=%"
Set "Title=%Title:\=%"
Set "Title=%Title::=%"
Set "Title=%Title:/=%"
Set "Title=%Title:"=%"
ECHO %Title%

Open in new window

~bp
Of course.
The idea of using the FOR loop was that it was easier to add more characters later. The only problem was that the FOR loop cannot be used on some of the special characters.
Avatar of ReneGe

ASKER

Thanks bp and Tommy :)

Cheers
A slightly improved solution would have been:

@echo off

set title="T\h:i|s< >i&s ^a t"e!s/t:"
echo %title%

set title="%title:"=%"
set title=%title:>=%
set title=%title:<=%
set title=%title:|=%
set title=%title:^=%
set title=%title:&=%
set title=%title:\=%
set title=%title::=%
set title=%title:!=%
set title=%title:/=%
set title=%title:"=%
echo %title%

Open in new window


But I forgot to post this comment yesterday!

As you can see, there is no need to delay expansion of variables, no need to a FOR-loop and no need to precede 'special' characters with a ceret (^) - all that is merely required is to wrap your whole character string in double-quotes.

The only other thing to note is the order in which to substitute out characters - especially the first few.