awk学习笔记

来源:互联网 发布:2016网络十大神曲逆 编辑:程序博客网 时间:2024/06/26 03:15

1、将第一列重复的元素去掉,只保留第一个

[root@CentOS awk_test]# cat sed_u.txt
haha;1
nihao;1
haha;3
hehe;4
heihei;5
heihei;6
1;HAHA
1;HEIHEI
[root@CentOS awk_test]# awk -F";" '!a[$1]++' sed_u.txt
haha;1
nihao;1
hehe;4
heihei;5
1;HAHA
[root@CentOS awk_test]#

2、AWK基础

[root@CentOS awk_test]# nl grade.txt
     1 M.Tans 5/99 48311 Green 8 40 44
     2 J.Lulu 06/99 48317 green 9 24 26
     3 P.Bunny 02/99 48 Yellow 12 35 28
     4 J.Troll 07/99 4842 Brown-3 12 26 26
     5 L.Tansl 05/99 4712 Brown-2 12 30 28
[root@CentOS awk_test]# awk 'BEGIN {print "Name Belt\n--"}{print $1"\t",$4}END{print "--end"}' grade.txt
Name Belt
--
M.Tans  Green
J.Lulu  green
P.Bunny  Yellow
J.Troll  Brown-3
L.Tansl  Brown-2
--end
[root@CentOS awk_test]#

[root@CentOS awk_test]# awk '$0~/Brown/ {print}' grade.txt
J.Troll 07/99 4842 Brown-3 12 26 26
L.Tansl 05/99 4712 Brown-2 12 30 28
[root@CentOS awk_test]# awk '{if($4~/Brown/) print $0}' grade.txt
J.Troll 07/99 4842 Brown-3 12 26 26
L.Tansl 05/99 4712 Brown-2 12 30 28
[root@CentOS awk_test]#

[root@CentOS awk_test]# awk '$0 !~ /Brown/' grade.txt
M.Tans 5/99 48311 Green 8 40 44
J.Lulu 06/99 48317 green 9 24 26
P.Bunny 02/99 48 Yellow 12 35 28
[root@CentOS awk_test]#

[root@CentOS awk_test]# awk '$6 < $7 {print $0}' grade.txt
M.Tans 5/99 48311 Green 8 40 44
J.Lulu 06/99 48317 green 9 24 26
[root@CentOS awk_test]#

[root@CentOS awk_test]#
[root@CentOS awk_test]# awk '/[Gg]reen/' grade.txt
M.Tans 5/99 48311 Green 8 40 44
J.Lulu 06/99 48317 green 9 24 26
[root@CentOS awk_test]#

[root@CentOS awk_test]#
[root@CentOS awk_test]# awk '$0 ~/(Yellow|Brown)/' grade.txt
P.Bunny 02/99 48 Yellow 12 35 28
J.Troll 07/99 4842 Brown-3 12 26 26
L.Tansl 05/99 4712 Brown-2 12 30 28
[root@CentOS awk_test]#

[root@CentOS awk_test]#
[root@CentOS awk_test]# awk '{print NF,NR,$0} END{print FILENAME}' grade.txt
7 1 M.Tans 5/99 48311 Green 8 40 44
7 2 J.Lulu 06/99 48317 green 9 24 26
7 3 P.Bunny 02/99 48 Yellow 12 35 28
7 4 J.Troll 07/99 4842 Brown-3 12 26 26
7 5 L.Tansl 05/99 4712 Brown-2 12 30 28
grade.txt
[root@CentOS awk_test]#

[root@CentOS awk_test]#

[root@CentOS awk_test]# echo $PWD
/lxg/awk_test
[root@CentOS awk_test]# echo $PWD | awk -F/
' {print $NF}'
awk_test
[root@CentOS awk_test]#

[root@CentOS awk_test]#
[root@CentOS awk_test]# awk '(tot+=$6); END{print "Club student total points :" tot}' grade.txt
M.Tans 5/99 48311 Green 8 40 44
J.Lulu 06/99 48317 green 9 24 26
P.Bunny 02/99 48 Yellow 12 35 28
J.Troll 07/99 4842 Brown-3 12 26 26
L.Tansl 05/99 4712 Brown-2 12 30 28
Club student total points :155
[root@CentOS awk_test]#

 

原创粉丝点击