We have a text file that we need containing the following sample. One constant string "D80" followed by another string:
D80KAAAAAA
D80KBBBBBB
D80KCCCCCCWe want to extract it using a Windows batch script file (not powershell) and FOR loop to get this output:
AAAAAA
BBBBBB
CCCCCCSo far we have gotten to this point. For illustration, i have shown the different attempts at extracting the substring:
setlocal EnableDelayedExpansion
for /F "tokens=1 delims=" %%a in (TPLIST.txt) do ( echo %%a echo %%(a:~4,6) set substr1=%%(a:~4,6)% set substr2=%(a:~4,6)% set substr3=!(a:~4,6)! set substr4=%!(a:~4,6)!% echo %substr1% echo %substr2% echo %substr3% echo %substr4%
)However, the extract of the substring fails:
C:\User>setlocal EnableDelayedExpansion
C:\User>for /F "tokens=1 delims=" %a in (TPLIST.txt) do (
echo %a echo %(a:~4,6
)
C:\User>(
echo D80KAAAAAA echo %(a:~4,6
)
D80KAAAAAA
%(a:~4,6
C:\User>(
echo D80KBBBBBB echo %(a:~4,6
)
D80KBBBBBB
%(a:~4,6
C:\User>(
echo D80KCCCCCC echo %(a:~4,6
)
D80KCCCCCC
%(a:~4,6
C:\User>set substr1=%(a:~4,6)
C:\User>set substr2=~4,6)
C:\User>set substr3=!(a:~4,6)!
C:\User>set substr4=~4,6)!
C:\User>echo %(a:~4,6)
%(a:~4,6)
C:\User>echo ~4,6)
~4,6)
C:\User>echo ~4,6)
~4,6)
C:\User>echo ~4,6)
~4,6)Any help would be greatly appreciated.
2 Answers
Howdo I extract a substring?
Your script is horribly broken so I rewrote it:
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2,3" %%a in (test.txt) do ( set _s1=%%a set _s2=%%b set _s3=%%c echo !_s1:~4! echo !_s2:~4! echo !_s3:~4! )
endlocalExample usage:
F:\test>type test.txt
D80KAAAAAA D80KBBBBBB D80KCCCCCC
F:\test>test
AAAAAA
BBBBBB
CCCCCC
F:\test>Further Reading
- An A-Z Index of the Windows CMD command line | SS64.com
- Windows CMD Commands (categorized) - Windows CMD - SS64.com
- For /f - Loop through text - Windows CMD - SS64.com
- variable substring - Windows CMD - SS64.com
In Pure batch file you can do something like that :
@echo off
Set "InputFile=TPLIST.txt"
Set "OutPutFile=%~dp0Out-Extract.txt"
setlocal enabledelayedexpansion
> "%OutPutFile%" ( @for /f "delims=" %%a in ('Type "%InputFile%"') do ( set "_MyString=%%a" echo !_MyString:~4! )
)
endlocal
If Exist "%OutPutFile%" Start "" "%OutPutFile%"In Powershell if another member wants to test using RegEx:
cls
$MyString = @'
D80KAAAAAA
D80KBBBBBB
D80KCCCCCC
D80KDDDDDD
D80KEEEEEE
D80KFFFFFF
D80KXXXXXX
D80KYYYYYY
D80KZZZZZZ
'@ -split [System.Environment]::NewLine
$pattern = '(?![D80K]).+'
$MyString | %{ [regex]::matches($_,$pattern) } | %{ $_.Groups[0].Value }You will get as output for both solutions batch or powershell like that :
1AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF XXXXXX YYYYYY ZZZZZZ