awk

From NetBSD Wiki

Jump to: navigation, search

The awk(1) utility can be used to match and process lines according to patterns. NetBSD's version of awk is nawk.

Examples

Print only certain "fields":

$ who | awk '{print $1,$2}'
root console
root ttyE1
root ttyp0
root ttyp1
mars ttyp2

Summing up values:

$ ifconfig -avu | egrep 'input|output' | awk \
'/input:/ {rx += $4} \
/output:/ {tx += $4} \
END {print "if traffic: "rx/1024/1024"MB in",tx/1024/1024"MB out"}'
if traffic: 48377.5MB in 44077.8MB out

This script will match the input and output lines from ifconfig and sum up the fourth field ($4 = bytes transferred). When it finishes (END block) it will display the traffic in MB.

Alternate example using if/else statement:

$ ifconfig -avu | egrep 'input|output' | awk \
'{if ($1 == "input:") rx += $4; else tx += $4} \
END {print "if traffic: "rx/1024/1024"MB in",tx/1024/1024"MB out"}'
if traffic: 48471.5MB in 44187.1MB out

In this case we use the if/else statement instead of pattern matching. If the first field is "input:" we increment the rx variable, else the tx.

Using custom field separators:

$ uptime | awk -v FS='averages:' '{print $2}'
0.88, 1.00, 0.93

See also

View source code (Please report any bugs or suggestions here).

Retrieved from "http://wiki.netbsd.se/awk"
Personal tools