Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
6.3.4. User defined variables<br />
<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />
Apart from the built-in variables, you can define your own. When awk encounters a reference to a variable<br />
which does not exist (which is not predefined), the variable is created and initialized to a null string. For all<br />
subsequent references, the value of the variable is whatever value was assigned last. Variables can be a string<br />
or a numeric value. Content of input fields can also be assigned to variables.<br />
Values can be assigned directly using the = operator, or you can use the current value of the variable in<br />
combination with other operators:<br />
kelly@octarine ~> cat revenues<br />
20021009 20021013 consultancy BigComp 2500<br />
20021015 20021020 training EduComp 2000<br />
20021112 20021123 appdev SmartComp 10000<br />
20021204 20021215 training EduComp 5000<br />
kelly@octarine ~> cat total.awk<br />
{ total=total + $5 }<br />
{ print "Send bill for " $5 " dollar to " $4 }<br />
END { print "---------------------------------\nTotal revenue: " total }<br />
kelly@octarine ~> awk -f total.awk test<br />
Send bill for 2500 dollar to BigComp<br />
Send bill for 2000 dollar to EduComp<br />
Send bill for 10000 dollar to SmartComp<br />
Send bill for 5000 dollar to EduComp<br />
---------------------------------<br />
Total revenue: 19500<br />
kelly@octarine ~><br />
C-like shorthands like VAR+= value are also accepted.<br />
6.3.5. More examples<br />
The example from Section 5.3.2 becomes much easier when we use an awk script:<br />
kelly@octarine ~/html> cat make-html-from-text.awk<br />
BEGIN { print "\nAwk-generated HTML\n<br />
{ print $0 }<br />
END { print "\n\n" }<br />
And the command to execute is also much more straightforward when using awk instead of sed:<br />
kelly@octarine ~/html> awk -f make-html-from-text.awk testfile > file.html<br />
Awk examples on your system<br />
We refer again to the directory containing the initscripts on your system. Enter a command similar to the<br />
following to see more practical examples of the widely spread usage of the awk command:<br />
grep awk /etc/init.d/*<br />
Chapter 6. The GNU awk programming language 76