shell实例三:awk
时间:2007-04-11 来源:codfei
awk
[root@better chap05]# date
一 3月 26 02:14:07 CST 2007
[root@better chap05]# date|awk '{print "Date:" $6 "\nTime:" $4}'
Date:2007
Time:02:14:16
[root@better chap05]# df
Filesystem 1K-块 已用 可用 已用% 挂载点
/dev/mapper/VolGroup00-LogVol00
7579576 1895616 5298936 27% /
/dev/sda1 101086 9046 86821 10% /boot
none 128056 0 128056 0% /dev/shm
[root@better chap05]# df -k |awk '$4>124000'
Filesystem 1K-块 已用 可用 已用% 挂载点
7579576 1895616 5298936 27% /
none 128056 0 128056 0% /dev/shm
[root@better chap05]# 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
[root@better chap05]# awk '/Sally/{print "\t\tHave a niceday,"$1,$2"!"}' employees
Have a niceday,Sally Chang!
[root@better chap05]# echo UNIX | awk '{printf "|%-15s|\n",$1}'
|UNIX |
[root@better chap05]# awk '{printf "The name is %-15s ID is %8d\n",$1,$3}' employees
The name is Tom ID is 4424
The name is Mary ID is 5346
The name is Sally ID is 1654
The name is Billy ID is 1683
[root@better chap05]# cat awkfile
/^Mary/{print "Hello Mary!"}
{print $1, $2, $3}
[root@better chap05]# awk -f awkfile employees
Tom Jones 4424
Hello Mary!
Mary Adams 5346
Sally Chang 1654
Billy Black 1683
[root@better chap05]# awk '$1 ~/[Bb]ill/' employees //第一域与Bill或bill匹配的行
Billy Black 1683 9/23/44 336500
[root@better chap05]# awk '$1 !~/ly$/' employees //匹配第一个域中结尾不是ly的行
Tom Jones 4424 5/12/66 543354
Mary Adams 5346 11/4/63 28765
[root@better chap05]# 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
[root@better chap05]# more info
# Here is a sample script:
#**************************************************************** *
# My first awk script by Codfei
# Script name: info; Date: February 28, 1999
/Tom/{print "Tom's birthday is " $3}
/Mary/{print NR, $0}
/^Sally/{print "Hi Sally, " $1 " has a salary of $" $4 "."}
#End of script
[root@better chap05]# awk -f info employees
Tom's birthday is 4424
2 Mary Adams 5346 11/4/63 28765
Hi Sally, Sally has a salary of $7/22/54.