1 To display the lines of a file that are longer than 72 characters, enter:
awk 'length >72' chapter1
This selects each line of the chapter1 file that is longer than 72 characters and
writes these lines to standard output, because no Action is specified. A tab character
is counted as 1 byte.
2 To display all lines between the words start and stop, including "start" and "stop",
enter:
awk '/start/,/stop/' chapter1
3 To run an awk command program, sum2.awk, that processes the file, chapter1, enter:
awk -f sum2.awk chapter1
The following program, sum2.awk, computes the sum and average of the numbers in the
second column of the input file, chapter1:
{
sum += $2
}
END {
print "Sum: ", sum;
print "Average:", sum/NR;
}
The first action adds the value of the second field of each line to the variable sum.
All variables are initialized to the numeric value of 0 (zero) when first referenced.
The pattern END before the second action causes those actions to be performed after
all of the input file has been read. The NR special variable, which is used to
calculate the average, is a special variable specifying the number of records that
have been read.
4 To print the first two fields in opposite order, enter:
awk '{ print $2, $1 }' chapter1
5 The following awk program
awk -f sum3.awk chapter2
prints the first two fields of the file chapter2 with input fields separated by comma
and/or blanks and tabs, and then adds up the first column, and prints the sum and
average:
BEGIN {FS = ",|[ \t]+"}
{print $1, $2}
{s += $1}
END {print "sum is",s,"average is", s/NR }
No comments:
Post a Comment