gawk: Array Example
1
1 8.1.4 Basic Array Example
1 -------------------------
1
1 The following program takes a list of lines, each beginning with a line
1 number, and prints them out in order of line number. The line numbers
1 are not in order when they are first read--instead, they are scrambled.
1 This program sorts the lines by making an array using the line numbers
1 as subscripts. The program then prints out the lines in sorted order of
1 their numbers. It is a very simple program and gets confused upon
1 encountering repeated numbers, gaps, or lines that don't begin with a
1 number:
1
1 {
1 if ($1 > max)
1 max = $1
1 arr[$1] = $0
1 }
1
1 END {
1 for (x = 1; x <= max; x++)
1 print arr[x]
1 }
1
1 The first rule keeps track of the largest line number seen so far; it
1 also stores each line into the array 'arr', at an index that is the
1 line's number. The second rule runs after all the input has been read,
1 to print out all the lines. When this program is run with the following
1 input:
1
1 5 I am the Five man
1 2 Who are you? The new number two!
1 4 . . . And four on the floor
1 1 Who is number one?
1 3 I three you.
1
1 Its output is:
1
1 1 Who is number one?
1 2 Who are you? The new number two!
1 3 I three you.
1 4 . . . And four on the floor
1 5 I am the Five man
1
1 If a line number is repeated, the last line with a given number
1 overrides the others. Gaps in the line numbers can be handled with an
1 easy improvement to the program's 'END' rule, as follows:
1
1 END {
1 for (x = 1; x <= max; x++)
1 if (x in arr)
1 print arr[x]
1 }
1