152} How can I remove all !:s and &:s from a text file with a script?
Special characters among &()[]{}^=;!'+,`~ in a text file may cause
problems when the text file is processed with a CLI script. A
SED solution can be used:
sed -e "s/[\x21\x26]//g" C:\_M\MyText.txt
The character code values for ! and & respectively are in
hexadecimal (
21, 26). Given a text file like
Hello World & others! Scripting is fun!
the output would be
Hello World
others Scripting is fun
Another situation applying SED. Say that you wished to substitute
all the @ characters with %40 in a file. Then
@echo off
sed -e "s/@/%%40/g" C:\_M\MyText.txt
Note the doubles in %%40 when within a script.
A Visual Basic Script (VBScript) aided solution can
be used so that third party utilities are not needed
@echo off & setlocal enableextensions
rem C:\_M\TEST\CMDTEST.CMD
::
set myfile_=C:\_M\TEST\My Test File.txt
::
:: Build a Visual Basic Script
set skip=
set vbs_=%temp%\tmp$$$.vbs
>"%vbs_%" findstr "'%skip%VBS" "%~f0"
::
:: Run it with Microsoft Windows Script Host Version 5.6
<"%myfile_%" cscript //nologo "%vbs_%"
::
:: Clean up
for %%f in ("%vbs_%") do if exist %%f del %%f
endlocal & goto :EOF
'
'............................................
'The Visual Basic Script
'
Do While Not WScript.StdIn.AtEndOfStream 'VBS
str = WScript.StdIn.ReadLine 'VBS
str = Replace (str, "&","") 'VBS
str = Replace (str, "!","") 'VBS
WScript.StdOut.WriteLine str 'VBS
Loop 'VBS
C:\_M\TEST>type "My Test File.txt"
This & is ! line & 1
This & is ! line & 2
"& and ! this & is ! line 3"
C:\_M\TEST>cmdtest
This is line 1
This is line 2
" and this is line 3"
One further question (also see
item #34). How does one include removing
quotes (") in the above VBS solution? One has to use the (decimal)
Chr function:
@echo off & setlocal enableextensions
rem C:\_M\TEST\CMDTEST.CMD
::
set myfile_=C:\_M\TEST\My Test File.txt
::
:: Build a Visual Basic Script
set skip=
set vbs_=%temp%\tmp$$$.vbs
>"%vbs_%" findstr "'%skip%VBS" "%~f0"
::
:: Run it with Microsoft Windows Script Host Version 5.6
<"%myfile_%" cscript //nologo "%vbs_%"
::
:: Clean up
for %%f in ("%vbs_%") do if exist %%f del %%f
endlocal & goto :EOF
'
'............................................
'The Visual Basic Script
'
Do While Not WScript.StdIn.AtEndOfStream 'VBS
str = WScript.StdIn.ReadLine 'VBS
str = Replace (str, "&","") 'VBS
str = Replace (str, "!","") 'VBS
str = Replace (str, Chr(34),"") 'VBS
WScript.StdOut.WriteLine str 'VBS
Loop 'VBS
C:\_M\TEST>cmdtest
This is line 1
This is line 2
and this is line 3