创建sample问价为例:
[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中的每一行打印第一个项目($ 1),然后打印第二个最后一个项目$(NF-1)
#awk '{print $1, $(NF-1) }' sample.txt
Sample Line
Sample Line
Sample Line
2、从文件打印非空行
awk 'NF > 0' sample.txt
3、印最长输入线的长度
awk '{ if (length($0) > max) max = length($0) } END { print max }' sample.txt
4、要从零到100(包括)打印七个随机数
awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
5、打印行数
awk 'END { print NR }' sample.txt
6、打印每行长度超过80个字符
awk 'length($0) > 80' data
7、打印文件中最长的行
awk '{ if (length($0) > max) max = length($0) } END { print max }' file
8、打印数据中最长行的长度
expand data | awk '{ if (x < length($0)) x = length($0) } END { print "maximum line length is " x }'
9、打印每行至少包含一个字段的行
awk 'NF > 0' data
awk 'NF > 0' data
10、打印文件使用的总字节数:
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数
ls -l /etc | awk '{ x += $5 } END { print "total K-bytes:", x / 1024 }'
12、打印所有用户的登录名的排序列表
awk -F: '{ print $1 }' /etc/passwd | sort
13、打印文件的行数
awk 'END { print NR }' data
14、打印包括11或88所在行
awk '/11/ { print $0 } /88/ { print $0 }' data
15、列出当前目录十二月份所有文件的总大小
ls -l | awk '$6 == "Nov" { sum += $5 }END { print sum }'
16、文件内容替换
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、