21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

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

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

Chapter 3: Reading Input Files 413.4 Changing the Contents of a FieldThe contents of a field, as seen by awk, can be changed within an awk program; this changeswhat awk perceives as the current input record. (The actual input is untouched; awk nevermodifies the input file.) Consider the following example and its output:$ awk ’{ nboxes = $3 ; $3 = $3 - 10> print nboxes, $3 }’ inventory-shipped⊣ 25 15⊣ 32 22⊣ 24 14...The program first saves the original value of field three in the variable nboxes. The ‘-’sign represents subtraction, so this program reassigns field three, $3, as the original valueof field three minus ten: ‘$3 - 10’. (See Section 5.5 [Arithmetic Operators], page 81.) Thenit prints the original and new values for field three. (Someone in the warehouse made aconsistent mistake while inventorying the red boxes.)For this to work, the text in field $3 must make sense as a number; the string of charactersmust be converted to a number for the computer to do arithmetic on it. The numberresulting from the subtraction is converted back to a string of characters that then becomesfield three. See Section 5.4 [Conversion of Strings and Numbers], page 79.When the value of a field is changed (as perceived by awk), the text of the input recordis recalculated to contain the new field where the old one was. In other words, $0 changesto reflect the altered field. Thus, this program prints a copy of the input file, with 10subtracted from the second field of each line:$ awk ’{ $2 = $2 - 10; print $0 }’ inventory-shipped⊣ Jan 3 25 15 115⊣ Feb 5 32 24 226⊣ Mar 5 24 34 228...It is also possible to also assign contents to fields that are out of range. For example:$ awk ’{ $6 = ($5 + $4 + $3 + $2)> print $6 }’ inventory-shipped⊣ 168⊣ 297⊣ 301...We’ve just created $6, whose value is the sum of fields $2, $3, $4, and $5. The ‘+’ signrepresents addition. For the file ‘inventory-shipped’, $6 represents the total number ofparcels shipped for a particular month.Creating a new field changes awk’s internal copy of the current input record, which isthe value of $0. Thus, if you do ‘print $0’ after adding a field, the record printed includesthe new field, with the appropriate number of field separators between it and the previouslyexisting fields.This recomputation affects and is affected by NF (the number of fields; see Section 3.2[Examining Fields], page 39). For example, the value of NF is set to the number of the

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

Saved successfully!

Ooh no, something went wrong!