25.03.2013 Views

Copyright Sams Teach Yourself Shell Programming in 24 Hours

Copyright Sams Teach Yourself Shell Programming in 24 Hours

Copyright Sams Teach Yourself Shell Programming in 24 Hours

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

P<strong>in</strong>eapple $1.29 35 REORDER<br />

Apple $0.99 78<br />

Compound Expressions<br />

Often you need to comb<strong>in</strong>e two or more expressions to check for a particular condition. When<br />

you comb<strong>in</strong>e two or more expressions, the result is called a compound expression .<br />

Compound expressions are constructed by us<strong>in</strong>g either the && (and) or the || (or) compound operators.<br />

The syntax is<br />

(expr1) && (expr2)<br />

(expr2) || (expr2)<br />

Here expr1 and expr2 are expressions constructed us<strong>in</strong>g the conditional operators given <strong>in</strong> Table 17.1.<br />

The parentheses surround<strong>in</strong>g expr1 and expr2 are required.<br />

When the && operator is used, both expr1 and expr2 must be true for the compound expression to be<br />

true. When the || operator is used, the compound expression is true if either expr1 or expr2 is true.<br />

As an example of us<strong>in</strong>g a compound expression, you can use the compound operators to obta<strong>in</strong> a list of all<br />

the fruit that cost more than a dollar and of which there are less than 75:<br />

awk '<br />

($2 ~ /^\$[1-9][0-9]*\.[0-9][0-9]$/) && ($3 < 75) {<br />

pr<strong>in</strong>tf "%s\t%s\t%s\n",$0,"*","REORDER" ;<br />

}<br />

' fruit_prices.txt ;<br />

The output looks like the follow<strong>in</strong>g<br />

Kiwi $1.50 22 * REORDER<br />

P<strong>in</strong>eapple $1.29 35 * REORDER<br />

The Compound Expression Operators<br />

You might hear the && operator called the and-and operator because it consists of two ampersands ( and<br />

characters). Similarly, the || operator might be referred to as the or-or operator.<br />

The next Command<br />

Consider the follow<strong>in</strong>g script:<br />

#!/b<strong>in</strong>/sh<br />

awk '<br />

$3 75 { pr<strong>in</strong>t $0 ; }<br />

' fruit_prices.txt

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

Saved successfully!

Ooh no, something went wrong!