創(chuàng)建sample問(wèn)價(jià)為例:
[root@log ~]#cat sample.txt
Sample Line 1
Sample Line 2
Sample Line 3
[root@log ~]#awk '{print NR "- " $1 }' sample.txt
1- Sample
2- Sample
3- Sample
1甘萧、從sample.txt中的每一行打印第一個(gè)項(xiàng)目($ 1),然后打印第二個(gè)最后一個(gè)項(xiàng)目$(NF-1)
#awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line
2、從文件打印非空行
awk 'NF > 0' sample.txt
3轧铁、印最長(zhǎng)輸入線的長(zhǎng)度
awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
4兵拢、要從零到100(包括)打印七個(gè)隨機(jī)數(shù)
awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
5溅话、打印行數(shù)
awk 'END { print NR }' sample.txt
6缎讼、打印每行長(zhǎng)度超過(guò)80個(gè)字符
awk 'length($0) > 80' data
7澎语、打印文件中最長(zhǎng)的行
awk '{ if (length($0) > max) max = length($0) } END { print max }' file
8熊户、打印數(shù)據(jù)中最長(zhǎng)行的長(zhǎng)度
expand data | awk '{ if (x < length($0)) x = length($0) } END { print "maximum line length is " x }'
9瓤球、打印每行至少包含一個(gè)字段的行
awk 'NF > 0' data
awk 'NF > 0' data
10、打印文件使用的總字節(jié)數(shù):
ls -l files | awk '{ x += $5 } END { print "total bytes: " x }'
ls -l /path | awk '{ x += $5 } END { print "total bytes: " x }'?
11敏弃、打印/etc下文件使用的總KB數(shù)
ls -l /etc | awk '{ x += $5 } END { print "total K-bytes:", x / 1024 }'
12卦羡、打印所有用戶的登錄名的排序列表
awk -F: '{ print $1 }' /etc/passwd | sort
13、打印文件的行數(shù)
awk 'END { print NR }' data
14麦到、打印包括11或88所在行
awk '/11/ { print $0 } /88/ { print $0 }' data
15绿饵、列出當(dāng)前目錄十二月份所有文件的總大小
ls -l | awk '$6 == "Nov" { sum += $5 }END { print sum }'
16、文件內(nèi)容替換
echo aaaabcd | awk '{ sub(/a+/, "A"); print }'
Record = record 1 and RT = [ AAAA ]
Record = record 2 and RT = [ BBBB ]
Record = record 3 and RT = [
]
[root@log /]#echo a b c d e f | awk '{ print "NF =", NF;NF = 3; print $0 }'
NF = 6
a b c
18拟赊、