学习awk命令的技巧,重在实践,勤于练习,多用awk去分析处理数据文件,慢慢就会熟能生巧。
$ awk '/diglike/,/redis/' /etc/passwd
diglike:x:1000:1000:DigLike,,,:/home/diglike:/bin/bash guest-M88sjb:x:115:125:Guest,,,:/tmp/guest-M88sjb:/bin/bash mongodb:x:116:65534::/home/mongodb:/bin/false redis:x:117:127:redis server,,,:/var/lib/redis:/bin/false 2、打印以dig或root开头的行:
awk '/^(root|dig)/' /etc/passwd
root:x:0:0:root:/root:/bin/bash diglike:x:1000:1000:DigLike,,,:/home/diglike:/bin/bash
3、打印以d或m开头的用户
$ awk -F: '/^[dm]/{print $1}' /etc/passwd | sort
daemon diglike man memcache messagebus mongodb
4、打印后两们是数字的用户
$ awk -F: '$1 ~/[0-9][0-9]$/{print $1}' /etc/passwd
ubuntu99
5、查找包含diglike的行,并将第三个域加100打印出来
$ awk -F: '/diglike/{print $3 + 100}' /etc/passwd
1100
6、匹配包含diglike的行,根据第三个域大小输出内容
$ awk -F: '/diglik/' /etc/passwd
diglike:x:1000:1000:DigLike,,,:/home/diglike:/bin/bash $ awk -F: '/diglike/{print($3>999?"ok"$3:"error"$3)}' /etc/passwd ok1000
7、变量赋值
$ awk -F: '$1 ~/^diglike/{count = $3 + $4;print count}' /etc/passwd
2000
8、域变量赋值
$ awk -F: '{$3 = $4 + 10;print}' /etc/passwd | head -1
root x 10 0 root /root /bin/bash
9、begin模块
diglike@LinuxGit:~$ awk 'BEGIN{FS=":";OFS="\t";ORS="\n\n"}{print $1,$3}' /etc/passwd | head -3 daemon 1
10、打印标题
$ awk 'BEGIN{print "Open Source"}'
Open Source
11、END模块
$ awk 'END{print "The number of records is " NR}' /etc/passwd
The number of records is 37 diglike@LinuxGit:~$ wc -l /etc/passwd 37 /etc/passwd
12、重定向:
复制代码代码示例:
diglike@LinuxGit:~$ awk -F: '$3==1000 {print $0 > "user_file"}' /etc/passwd
diglike@LinuxGit:~$ cat user_file diglike:x:1000:1000:DigLike,,,:/home/diglike:/bin/bash
13、管道:
$ awk 'BEGIN{"date"|getline d;split(d, mon);print mon[2]}'
$ awk 'BEGIN{while("ls"|getline) print}'
$ awk 'BEGIN{while(getline<"/etc/passwd">0) count++;print count}' getline从标准输入、管道或者当前正在处理的文件之外的其他输入文件获得输入。它负责从输入获得下一行的内容,并给NF,NR和FNR等内建变量赋值。如果得到一条记录,getline函数返回1,如果到达文件的末尾就返回0,如果出现错误,例如打开文件失败,就返回-1。
14、执行系统命令:
$ awk 'BEGIN{system("clear")}'
15、if语句
$ awk -F: '{if($3<$4) print $1}' /etc/passwd
sync games man libuuid syslog messagebus colord lightdm whoopsie avahi-autoipd avahi kernoops pulse rtkit saned mongodb redis memcache dnsmasq
更简洁:
diglike@LinuxGit:~$ awk -F: '$3<$4{print $1}' /etc/passwd
if else $ awk -F: '{if($3==$4){print $1 " yes"} else {print $1 " no"}}' /etc/passwd
更简洁的代码:
$ awk -F: '{print ($3==$4?$1 " yes":$1 " no")}' /etc/passwd | head -5
for while (责任编辑:IT) |