Extract String and Variable Substitution

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Extract String and Variable Substitution

#1 Post by darioit » 03 Aug 2010 04:57

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

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Extract String and Variable Substitution

#2 Post by jeb » 03 Aug 2010 05:28

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

ghostmachine4
Posts: 319
Joined: 12 May 2006 01:13

Re: Extract String and Variable Substitution

#3 Post by ghostmachine4 » 03 Aug 2010 06:09

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

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: Extract String and Variable Substitution

#4 Post by darioit » 03 Aug 2010 06:34

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?

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Extract String and Variable Substitution

#5 Post by jeb » 03 Aug 2010 07:19

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%

ghostmachine4
Posts: 319
Joined: 12 May 2006 01:13

Re: Extract String and Variable Substitution

#6 Post by ghostmachine4 » 03 Aug 2010 08:02

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


Post Reply