Loops: introduction and extrapolation
simplest loops
| command/output | explanation |
$ for i in a b c d e |
redefine $i successively as 'a', 'b', 'c', 'd', and 'e' repeat the commands following 'do' for each value of $i show the value of $i as we go |
$for i in happy ever after |
Looping on values given as space delimited list of strings. |
$echo happy ever after |
arguments given to loop variable are space delimited; each echo statement produces a new line. |
$echo happy ever after>afile |
above remark is true even when loop variable is initialized by `cat filename` |
| $for i in happy ever after; do echo $i:$i; done happy:happy ever:ever after:after | This shows we can double up and format the output, if so desired. |
grepping in a loop; taking advantage of above
| command/output | explanation |
| $ w=/home/SRUNET/david.dailey/words ~$wc $w 35916 35916 332173 /home/SRUNET/david.dailey/words | A familiar file consisting of about 36,000 English words (one per line) |
| $for i in happy ever after; do echo $i;grep $i $w|tail -1; done happy unhappy ever wherever after thereafter | For each of the three words 'happy', 'ever', and 'after', output it ($i) as well as the last word in the dictionary containing it. |
| $ for i in happy ever after; do echo $i `grep $i $w|tail -1`; done happy unhappy ever wherever after thereafter | echo-ing both the variable and its last dictionary occurrence on the same line of output. |
$for i in {a..e};
|
redefine $i successively as 'a', 'b', 'c', 'd', and 'e' repeat the commands following 'do' for each value of $i look for words in the dictionary beginning with $i and ending with 'dy'; count them; show an example. show the value of $i as we go |
$grep -c ^[a-e].*dy$ $w |
verification that the output makes sense. Note that 3+10+8+6+3=30. |