6.2.1 Input from Files
时间:2006-11-19 来源:h0ng123
In the following examples, the percent sign is a shell prompt. Please take note: In all examples where the command is nawk, use either awk or gawk if you are on an HP-UX flavor system or using Linux.
FORMAT
% nawk 'pattern' filename % nawk '{action}' filename % nawk 'pattern {action}' filename
Here is a sample file called employees:
Example 6.1.
% cat employees Tom Jones 4424 5/12/66 543354 Mary Adams 5346 11/4/63 28765 Sally Chang 1654 7/22/54 650000 Billy Black 1683 9/23/44 336500 % nawk '/Mary/' employees Mary Adams 5346 11/4/63 28765
EXPLANATION
Nawk prints all lines that contain the pattern Mary.
Example 6.2.
% cat employees Tom Jones 4424 5/12/66 543354 Mary Adams 5346 11/4/63 28765 Sally Chang 1654 7/22/54 650000 Billy Black 1683 9/23/44 336500 % nawk '{print $1}' employees Tom Mary Sally Billy
EXPLANATION
Nawk prints the first field of file employees, where the field starts at the left margin of the line and is delimited by whitespace.
Example 6.3.
% cat employees Tom Jones 4424 5/12/66 543354 Mary Adams 5346 11/4/63 28765 Sally Chang 1654 7/22/54 650000 Billy Black 1683 9/23/44 336500 % nawk '/Sally/{print $1, $2}' employees Sally Chang
EXPLANATION
Nawk prints the first and second fields of file employees, only if the line contains the pattern Sally. Remember, the field separator is whitespace.
6.2.2 Input from Commands
The output from a UNIX/Linux command or commands can be piped to awk for processing. Shell programs commonly use awk for manipulating commands.
FORMAT
% command | nawk 'pattern' % command | nawk '{action}' % command | nawk 'pattern {action}'
Example 6.4.
1 % df | nawk '$4 > 75000' /oracle (/dev/dsk/c0t0d057 ):390780 blocks 105756 files /opt (/dev/dsk/c0t0d058 ):1943994 blocks 49187 files 2 % rusers | nawk '/root$/{print $1}' owl crow bluebird
EXPLANATION
-
The df command reports the free disk space on file systems. The output of the df command is piped to nawk. If the fourth field is greater than 75,000 blocks, the line is printed.
The rusers command prints those logged on remote machines on the network. The output of the rusers command is piped to nawk as input. The first field is printed if the regular expression root is matched at the end of the line ($); that is, all machine names are printed where root is logged on.
相关阅读 更多 +