Simple templates for parsing into words
parse value 'time and tide' with var1 var2 var3
The
template in this instruction is: var1 var2 var3.
The data to parse is between the keywords PARSE VALUE and
the keyword WITH, the source string time
and tide. Parsing divides the source string into blank-delimited
words and assigns them to the variables named in the template as follows:
var1='time'
var2='and'
var3='tide'
In this example, the source string to parse
is a literal string, time and tide. In the next example,
the source string is a variable. /* PARSE VALUE using a variable as the source string to parse */
string='time and tide'
parse value string with var1 var2 var3 /* same results */
(PARSE VALUE does not convert lowercase a–z in the source string to uppercase A–Z. If you want to convert characters to uppercase, use PARSE UPPER VALUE. See Using UPPER for a summary of the effect of parsing instructions on case.)
All of the parsing instructions assign the parts of a source string into the variables named in a template. There are various parsing instructions because of differences in the nature or origin of source strings. (A summary of all the parsing instructions is on page Parsing Instructions Summary.)
/* PARSE VAR example */
stars='Sirius Polaris Rigil'
parse var stars star1 star2 star3 /* star1='Sirius' */
/* star2='Polaris' */
/* star3='Rigil' */
/* More variables in template than (words in) the source string */
satellite='moon'
parse var satellite Earth Mercury /* Earth='moon' */
/* Mercury='' */
/* More (words in the) source string than variables in template */
satellites='moon Io Europa Callisto...'
parse var satellites Earth Jupiter /* Earth='moon' */
/* Jupiter='Io Europa Callisto...'*/
/* Preserving extra blanks */
solar5='Mercury Venus Earth Mars Jupiter '
parse var solar5 var1 var2 var3 var4
/* var1 ='Mercury' */
/* var2 ='Venus' */
/* var3 ='Earth' */
/* var4 =' Mars Jupiter ' */
In the source string, Earth has two leading blanks. Parsing removes both of them (the word-separator blank and the extra blank) before assigning var3='Earth'. Mars has three leading blanks. Parsing removes one word-separator blank and keeps the other two leading blanks. It also keeps all five blanks between Mars and Jupiter and both trailing blanks after Jupiter.
parse value ' Pluto ' with var1 /* var1=' Pluto '*/
The period as placeholder
- As a “dummy variable” in a list of variables
- Or to collect unwanted information at the end of a string.
/* Period as a placeholder */
stars='Arcturus Betelgeuse Sirius Rigil'
parse var stars . . brightest . /* brightest='Sirius' */
/* Alternative to period as placeholder */
stars='Arcturus Betelgeuse Sirius Rigil'
parse var stars drop junk brightest rest /* brightest='Sirius' */