11.23 foreach

foreach <variable> in ( <filename wildcard> |
                        <list> )
                      [ loopname <loopname> ]
  <code>

The foreach command can be used to run a block of commands repeatedly, once for each item in a list. The list of items can be specified in one of two ways. In the first case, a set of filenames or filename wildcards is supplied, and the foreach loop iterates once for each supplied filename, with a string variable set to each filename in succession. For example, the following loop would plot the data in the set of files whose names end with .dat:

plot     # Create blank plot
foreach file in *.dat
 {
  replot file with lines
 }

The second form of the command takes a list of string or numerical values provided explicitly by the user, and the foreach loop iterates once for each value, with a variable set to each value in succession. For example, the following script would plot normal distributions of three different widths:

plot     # Create blank plot
foreach sigma in (1, 2, 3)
 {
  replot 1/sigma*exp(-x**2/(2*sigma**2))
 }