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.

42 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>highest field you create. The exact format of $0 is also affected by a feature that hasnot been discussed yet: the output field separator, OFS, used to separate the fields (seeSection 4.3 [Output Separators], page 60).Note, however, that merely referencing an out-of-range field does not change the valueof either $0 or NF. Referencing an out-of-range field only produces an empty string. Forexample:if ($(NF+1) != "")print "can’t happen"elseprint "everything is normal"should print ‘everything is normal’, because NF+1 is certain to be out of range. (SeeSection 6.4.1 [The if-else Statement], page 102, for more information about awk’s ifelsestatements. See Section 5.10 [Variable Typing and Comparison Expressions], page 87,for more information about the ‘!=’ operator.)It is important to note that making an assignment to an existing field changes the valueof $0 but does not change the value of NF, even when you assign the empty string to a field.For example:$ echo a b c d | awk ’{ OFS = ":"; $2 = ""> print $0; print NF }’⊣ a::c:d⊣ 4The field is still there; it just has an empty value, denoted by the two colons between ‘a’and ‘c’. This example shows what happens if you create a new field:$ echo a b c d | awk ’{ OFS = ":"; $2 = ""; $6 = "new"> print $0; print NF }’⊣ a::c:d::new⊣ 6The intervening field, $5, is created with an empty value (indicated by the second pair ofadjacent colons), and NF is updated with the value six.Decrementing NF throws away the values of the fields after the new value of NF andrecomputes $0. Here is an example:$ echo a b c d e f | awk ’{ print "NF =", NF;> NF = 3; print $0 }’⊣ NF = 6⊣ a b cCaution: Some versions of awk don’t rebuild $0 when NF is decremented. Caveat emptor.Finally, there are times when it is convenient to force awk to rebuild the entire record,using the current value of the fields and OFS. To do this, use the seemingly innocuousassignment:$1 = $1 # force record to be reconstitutedprint $0 # or whatever else with $0This forces awk rebuild the record. It does help to add a comment, as we’ve shown here.There is a flip side to the relationship between $0 and the fields. Any assignment to$0 causes the record to be reparsed into fields using the current value of FS. This also

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

Saved successfully!

Ooh no, something went wrong!