Monday, 15 February 2010

How to split a string using values from variables? (Batch) -



How to split a string using values from variables? (Batch) -

i have variable acts line print, need edit individual characters in line via position in line. need utilize variables specify location each time, , cmd interprets variables wrong way.

@echo off set fv=0 set fh=1 set /a fh1=%fh%+1 set linev=line%fv% set line%fv%=%linev:~0,%fh%%%newcharacter%%linev:~%fh1%%

sorry code messy, hope understood. want cmd interpret code as: %fv% %fh% %newcharacter% %fh1% , turn 2 string manipulators substrings.

i'm not sure understand order of evaluation in lastly line of script sample, verbal explanation. however, think can @ to the lowest degree show you, using simple examples, how can accomplish want, , you'll work out how apply technique in situation.

basically, need utilize 2 kinds of expansion here: immediate (or % expansion) , delayed.

there's delayed expansion proper in batch files, must first enabled (typically using command setlocal enabledelayedexpansion) , utilize ! instead of % variable evaluation. consider next example:

set ind=1 set line%ind%=abc setlocal enabledelayedexpansion echo !line%ind%! endlocal

in above example, 2 variables created, ind , line1. sec name partly constructed using first variable. when setting value such variable, delayed expansion not needed, because name, left part of assignment, doesn't need evaluated. when need evaluated, need utilize delayed expansion. echo command in above script works this:

%ind% evaluated first;

as result of %ind% evaluation, command becomes echo !line1!;

since delayed expansion has been enabled, ! has special meaning, i.e. (delayed) variable evaluation, , !line1! evaluates abc;

echo prints abc.

although kind of delayed expansion preferred one, in above illustration can accomplish same using call-expansion. here's same illustration script rewritten utilize call-expansion:

set ind=1 set line%ind%=abc phone call echo %%line%ind%%%

basically, there's % expansion way, different parts evaluated @ different times. here's how sec example's delayed evaluation works:

the first %% turns %;

%ind% evaluated 1;

the remaining %% turns %;

call receives command execute: echo %line1%;

%line1% evaluates abc;

echo prints abc.

the call expansion slower, may manifest in loops. ! expansion, on other hand, has implications stemming particularly fact setlocal command used enable syntax. there's more on topic in my reply different question.

string batch-file

No comments:

Post a Comment