Page 1 of 1

Extract String and Variable Substitution

Posted: 03 Aug 2010 04:57
by darioit
Hello I have this problem to resolve

This is the input line
line = abcde1234fghil
%Rec1%=6 (pos. start number)
%Rec2%=4 (lengh data)

I want a new variable like this (%new_var% = 1234)

I write this code (is working fine with replace rec1 and rec2 with 6,4 but I want a variable because the position of number to extract changing
new_var = %line%:~%REC1%,%REC2%%

I try in many way to find out a correct result but none working, could you help me?

Thanks

Re: Extract String and Variable Substitution

Posted: 03 Aug 2010 05:28
by jeb
It is a litte bit tricky.

Code: Select all

@echo off
setlocal EnableDelayedExpansion
set line=abcde1234fghil
set Rec1=5
set Rec2=4
call set var1=%%line:~%Rec1%,%Rec2%%%
echo var1=%var1%

set var2=!line:~%Rec1%,%Rec2%!
echo var2=%var2%


Variant1 works because after the first expansion you got
call set var1=%line:~5,4%
And the "call" expands it a second time

Variant2 works because "!" works like "%", but first the "%var%" are expanded

hope it helps
jeb

Re: Extract String and Variable Substitution

Posted: 03 Aug 2010 06:09
by ghostmachine4
download sed for windows

then do this

Code: Select all

C:\test>echo abcd12345fghil|sed -r "s/.[^0-9]*([0-9]+).*/\1/"
12345

C:\test>echo abcde1234fghil|sed -r "s/.[^0-9]*([0-9]+).*/\1/"
1234


to store the result into a variable, use a for loop, which i am sure you can do it by yourself

Re: Extract String and Variable Substitution

Posted: 03 Aug 2010 06:34
by darioit
Perfect works fine, but if the data contains some 0 like abcd00045fghil how can I transform 00045 in a number for to be compared to other numeric data?

Re: Extract String and Variable Substitution

Posted: 03 Aug 2010 07:19
by jeb
You got problems, because numbers with prefixed "0" are interpreted as octal numbers

A simple way is to prepend a "1" to the number and then remove it mathematical.

Code: Select all

set line=abcd00045fghi
set var=1%line:~4,5%
set /a var=2*var - 2%var:~1%
echo var=%var%

Re: Extract String and Variable Substitution

Posted: 03 Aug 2010 08:02
by ghostmachine4
darioit wrote:Perfect works fine, but if the data contains some 0 like abcd00045fghil how can I transform 00045 in a number for to be compared to other numeric data?

Code: Select all

C:\test>echo abc0045fghil|sed -r "s/.[^0-9]*([0-9]+).*/\1/" | sed "s/^0*//"
45