But I was looking a way to detect and possibly remove or substitute the TAB characters without resorting to any external command or using literal TAB in the editor.
I came up with a solution, and It was simpler than I could imagine. Actually the detection does not require access to TAB character. For removal or substitution, the TAB character can be extracted the from the subject string itself so it is a fully self contained solution.
Here is the sample script to demonstrate the method. It is fully commented and is fairly simple to understand.
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set "String=!%~1!"
if not defined String (
echo Pass the name of the environment variable which contains one or more TAB characters
exit /b
)
:: Define LineFeed
set ^"LF=^%==%
%==%
%==%"
:: And the escaped one
set "eLF=^^!LF!!LF!"
:: Remove all Spaces
:: And surround the string between two ordinary chars
:: to ensure that there will be no leading or trailing TABs
set "testTAB=#!String: =!#"
:: Remove all double quotation marks
set "testTAB=!testTAB:"=!"
:: Remove all LineFeeds
set ^"testTAB=!testTAB:%eLF%=!"
:: Remove all Bangs !
set "hasBang="
if not "!testTAB!"=="!testTAB:*!=!" (
setlocal DisableDelayedExpansion
set "hasBang=1"
set "testTAB=%testTAB:!=%"
)
if defined hasBang (
endlocal
set "testTAB=%testTAB%"
)
:: Detecting the presence of TAB char in the string
set "hasTAB="
for /F "tokens=1,2" %%A in ("!testTAB!") do (
if not "%%B"=="" (
REM The default delimiters are <SPACE> and <TAB>
REM Since the string doesn not contain any <SPACE> chars,
REM A none empty second token proves the presence of the TAB char
set "hasTAB=1"
set "lead=%%A"
)
)
if defined hasTAB (
echo The String contains the TAB character
call :strlen len lead
REM Extract the TAB character from the String itself
for %%I in (!len!) do set "charTAB=!testTAB:~%%I,1!"
)
if defined hasTAB (
REM Now remove the TABs from the original string
set "noTabString=!String:%charTAB%=!"
echo Original String: [!String!]
echo After removing TABs: [!noTabString!]
)
exit /b
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
for %%L in (!len!) do (
endlocal
set "%~1=%%L"
)
exit /b
)