# Solved: Removing "!" from file name while using EnableDelayedExpansion



## miningold (Jul 6, 2010)

I am trying to remove the exclamation mark from file names using code similar to this:

```
SETLOCAL ENABLEDELAYEDEXPANSION
for /d %%i in (*) do (
  for /f "tokens=*" %%j in ('dir /b "%%i\*.flac"') do (
    set name=%%j
    set name=!name:^!=!
    rename %%j !name!
  )
)
```
(I know the code above does not work)
I want to remove the characters because I am trying to run commands like this:

```
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=*" %%k in ('dir /b *.flac') do (
  convertcommand "%%~nk" -!var1! -!var2!
)
```
(the code is generalized)
But some of the flac files have "!"s in them so it does not work


----------



## TheOutcaste (Aug 8, 2007)

Welcome to TSG!

Call a subroutine to do the rename and you don't need Delayed Expansion.


```
SetLocal DisableDelayedExpansion
For /D %%i In (*) Do (
  PushD %%i
  For /F "Tokens=*" %%j In ('Dir /B *.flac^|Findstr "!"') Do Call :_Rename "%%j"
  PopD
)
EndLocal
SetLocal EnableDelayedExpansion
For /D %%i In (*) Do (
:: Set var1 and var2 as needed
  PushD %%i
  For /F "Tokens=*" %%j In ('Dir /B *.flac') Do convertcommand "%%~nj" -!var1! -!var2!
  PopD
)
Goto :EOF
:_Rename
Set _Temp=%~1
Set _Temp=%_Temp:!=%
Ren "%~1" "%_Temp%"
```
And unless you are changing the var1 and var2 values inside the loop, you don't need delayed expansion there either, in which case this should work:

```
SetLocal DisableDelayedExpansion
For /D %%i In (*) Do (
  PushD %%i
  For /F "Tokens=*" %%j In ('Dir /B *.flac^|Findstr "!"') Do Call :_Rename "%%j"
  For /F "Tokens=*" %%j In ('Dir /B *.flac') Do convertcommand "%%~nj" -%var1% -%var2%
  PopD
)
Goto :EOF
:_Rename
Set _Temp=%~1
Set _Temp=%_Temp:!=%
Ren "%~1" "%_Temp%"
```
File names with an *&* will also cause problems, to remove the *&* and replace it with *And* use this:

```
SetLocal DisableDelayedExpansion
For /D %%i In (*) Do (
  PushD %%i
  For /F "Tokens=*" %%j In ('Dir /B *.txt^|Findstr "& !"') Do Call :_Rename "%%j"
  For /F "Tokens=*" %%j In ('Dir /B *.txt') Do convertcommand "%%~nj" -%var1% -%var2%
  PopD
)
Goto :Eof
:_Rename
Set _Temp="%~1"
Set _Temp=%_Temp:&=And%
Set _Temp=%_Temp:!=%
Set _Temp=%_Temp:~1,-1%
Ren "%~1" "%_Temp%"
```


----------



## miningold (Jul 6, 2010)

TheOutcaste said:


> Welcome to TSG!
> 
> Call a subroutine to do the rename and you don't need Delayed Expansion.
> 
> ...


This worked great thank you so much. I do need var1 and var2 changing each time I just did not include it. I also implemented the "&" symbol code.
Thanks again


----------

