27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

For a more extensive treatment of sed, check the appropriate references in the Bibliography.<br />

B.2. Awk<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

Awk is a full−featured text processing language with a syntax reminiscent of C. While it possesses an<br />

extensive set of operators and capabilities, we will cover only a couple of these here − the ones most useful<br />

for shell scripting.<br />

Awk breaks each line of input passed to it into fields. By default, a field is a string of consecutive characters<br />

separated by whitespace, though there are options for changing the delimiter. Awk parses and operates on<br />

each separate field. This makes awk ideal for handling structured text files, especially tables, data organized<br />

into consistent chunks, such as rows and columns.<br />

Strong quoting (single quotes) and curly brackets enclose segments of awk code within a shell script.<br />

awk '{print $3}' $filename<br />

# Prints field #3 of file $filename to stdout.<br />

awk '{print $1 $5 $6}' $filename<br />

# Prints fields #1, #5, and #6 of file $filename.<br />

We have just seen the awk print command in action. The only other feature of awk we need to deal with here<br />

is variables. Awk handles variables similarly to shell scripts, though a bit more flexibly.<br />

{ total += ${column_number} }<br />

This adds the value of column_number to the running total of "total". Finally, to print "total", there is an END<br />

command block, executed after the script has processed all its input.<br />

END { print total }<br />

Corresponding to the END, there is a BEGIN, for a code block to be performed before awk starts processing<br />

its input.<br />

For examples of awk within shell scripts, see:<br />

1. Example 11−10<br />

2. Example 16−7<br />

3. Example 12−24<br />

4. Example 34−3<br />

5. Example 9−22<br />

6. Example 11−16<br />

7. Example 28−1<br />

8. Example 28−2<br />

9. Example 10−3<br />

10. Example 12−42<br />

11. Example 9−26<br />

12. Example 12−3<br />

13. Example 9−12<br />

14. Example 34−11<br />

15. Example 10−8<br />

Appendix B. A Sed and Awk Micro−Primer 410

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!