说明:题目中引用的文件名为/etc/passwd和a,passwd记录了系统用户信息,a的内容是随意的打了几行英文,原文如下:
Red Hat Enterprise Linux Version 5.3
Get the latest news about the world's Open Source Leader
Red Hat Network
Manage your system dffectively through Red Hat Network
Global Learning Services
 You've got Red Hat Enterprise Linux,now get the skills
check out Red Hat's training courses and industry-acclaimed
2009082301
#This is a test456 line
     space test123 line234
 
1.编写一个awk脚本,功能是打印所有输入行
[root@Siegfried test]# awk '{print}' a
 
2.编写一个awk脚本,打印输入文件第八行
[root@Siegfried test]# awk 'NR==8{print}' a
 
3.用awk命令打印文件所有行的第一个字段
[root@Siegfried test]# awk -F\  '{print $1}' a
 
4.打印输入行总数
[root@Siegfried test]# awk 'END{print NR}' a
 
5.打印每行字段数
[root@Siegfried test]# awk -F\  '{print NF}' a
 
6.打印最后一行的最后一个字段的值
[root@Siegfried test]# awk 'END{print $NF}' a
 
7.打印字段数多于4个的行
[root@Siegfried test]# awk '{if(NF>4) print NR}' a
 
8.打印文件所有字段的总数
[root@Siegfried test]# awk -F\  'BEGIN{num=0; sum=0}{num=NF; sum=sum+num}END{print sum}' a
 
9.打印uid在30--40范围内的用户名
[root@Siegfried test]# awk -F: '{if($3>=30&&$3<=40)print $1}' /etc/passwd
 
10.倒序排列文件的所有字段
#!/bin/awk -f
        BEGIN{
                FS=" "

                }
                {
                                for(i=NF;i>0;i--){

                                        printf("%s%s",$i,FS)
                                        }
                                        printf("\n")
                }

11.打印3-8行
[root@Siegfried test]# awk '{if(NR>=3&&NR<=8)print}' a
 
12.在文件顶部加上标题“Document”
[root@Siegfried test]# awk 'BEGIN{print "Document"}{print}' a
 
13.隔行删除
[root@Siegfried test]# awk '{if(NR%2==0) print}' a
[root@Siegfried test]# awk '{if(NR%2==1) print}' a
 
14.每行抽取第一个单词
#!/bin/awk -f
        BEGIN{
                FS=" "
                }
                {
                        print $1
                }
 
15.打印每行的第一个和第三个单词
#!/bin/awk -f
        BEGIN{
                FS=" "
                }
                {
                        print ($1" "$3)
                }

16.打印字段数大于5个的行总数
[root@Siegfried test]# awk -F\  'BEGIN{num=0}{if(NF>5)num++}END{print num}' a