windows - Batch Replace of !-sign -


i trying remove character ! in variable.

setlocal enableextensions enabledelayedexpansion  set filename=!filename:!=_!  

i have tried escape ^ did not work.

set filename=!filename:^!=_! 

how can rid of !-sign in variable?

you cannot replace % when using normal expansion. must use delayed expansion insntead: !var:%%=_!

likewise, cannot replace ! when using delayed expansion. must use normal expansion instead: %var:!=_%.

but can problem if variable may contain mixture of poison characters ^, &, |, >, < quotes. example, there no single step way replace ! within following string: "this & that" & other thing!

the trick replacement in stages, using delayed expansion, 1 replacement using normal expansion.

1) delayed expansion - convert " ""

2) normal expansion - convert ! replacement. because quotes doubled, outer quotes around expansion guaranteed protect poison characters

3) delayed expansion - convert "" "

@echo off setlocal enabledelayedexpansion set "var="this ^& that" & other thing^!" echo before: !var!  set "var=!var:"=""!" set "var=%var:!=_%" set "var=!var:""="!"  echo  after: !var! 

-- output --

before: "this & that" & other thing!  after: "this & that" & other thing_ 

but dealing file names, can make problem simpler :-)

file names can contain poison characters & , ^, cannot contain quotes. can put quotes anywhere within file name (or path), , protect poison characters. quotes removed os when stores or looks files on disk.

so make sure file name , path variables not contain quotes. safe use:

set "filename=%filename:!=_%" 

oops - read question comments, , see within loop!

the fact substitution occurs within loop complicates things, since normal expansion not see values defined within loop.

note delayed expansion must off when variable expanded, otherwise corrupt ! within file name.

the simplest solution use call round of expansion:

@echo off setlocal disabledelayedexpansion %%f in (*) (   set "file=%%f"   call set "file=%%file:!=_%%"   setlocal enabledelayedexpansion   echo file=!file!   endlocal ) 

if doing other manipulations require delayed expansion, ! need escaped within normal expansion replacement expression because delayed expansion occurs before call. (thanks jeb).

here example eliminates ^ , & well.

@echo off setlocal disabledelayedexpansion %%f in (*) (   set "file=%%f"   setlocal enabledelayedexpansion   set "file=!file:^=_!"   set "file=!file:&= , !"   call set "file=%%file:^!=_%%"   echo file=!file!   endlocal ) 

although have enabled delayed expansion after have removed !. escape not needed.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -