21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Expressions 81decimal point character. (gawk also uses the locale’s decimal point character when in POSIXmode, either via ‘--posix’, or the POSIXLY_CORRECT environment variable.)The following table describes the cases in which the locale’s decimal point character isused and when a period is used. Some of these features have not been described yet.Feature Default ‘--posix’ or ‘--use-lc-numeric’‘%’g’ Use locale Use locale‘%g’ Use period Use localeInput Use period Use localestrtonum Use period Use localeTable 5.1: Locale Decimal Point versus A PeriodFinally, modern day formal standards and IEEE standard floating point representationcan have an unusual but important effect on the way gawk converts some special stringvalues to numbers. The details are presented in Section D.3.3 [Standards Versus ExistingPractice], page 304.5.5 Arithmetic OperatorsThe awk language uses the common arithmetic operators when evaluating expressions. Allof these arithmetic operators follow normal precedence rules and work as you would expectthem to.The following example uses a file named ‘grades’, which contains a list of student namesas well as three test scores per student (it’s a small class):Pat 100 97 58Sandy 84 72 93Chris 72 92 89This programs takes the file ‘grades’ and prints the average of the scores:$ awk ’{ sum = $2 + $3 + $4 ; avg = sum / 3> print $1, avg }’ grades⊣ Pat 85⊣ Sandy 83⊣ Chris 84.3333The following list provides the arithmetic operators in awk, in order from the highestprecedence to the lowest:- x Negation.+ x Unary plus; the expression is converted to a number.x ^ yx ** yx * yx / yExponentiation; x raised to the y power. ‘2 ^ 3’ has the value eight; the charactersequence ‘**’ is equivalent to ‘^’.Multiplication.Division; because all numbers in awk are floating-point numbers, the result isnot rounded to an integer—‘3 / 4’ has the value 0.75. (It is a common mistake,

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

Saved successfully!

Ooh no, something went wrong!