Awk學習(一)之基本使用
一、基本知識
NR: 檔案中記錄個數
NF:每一行欄位個數
二、測試檔案內容
test.txt:
zhangsan 20 lisi 19 wangwu 21
三、測試結果
1. awk '{print NR,$1,NF}' test.txt
1 zhangsan 2 2 lisi 2 3 wangwu 2
2. awk '$2 >= 20 {print $1,$2}' test.txt
zhangsan 20 wangwu 21
3. awk '$2 >= 20 {print "name:", $1,"age:", $2}' test.txt
name: zhangsan age: 20 name: wangwu age: 21
4. awk '$2 >= 20 {printf("name: %s age: %d\n", $1, $2)}' test.txt
name: zhangsan age: 20 name: wangwu age: 21
5. awk '$2 >= 20 {printf("name: %s age: %.1f\n", $1, $2)}' test.txt
name: zhangsan age: 20.0 name: wangwu age: 21.0
6. awk '{printf("name: %s age: %.1f\n", $1, $2)}' test.txt | sort
name: lisi age: 19.0 name: wangwu age: 21.0 name: zhangsan age: 20.0
7. awk '$2 > 20' test.txt
wangwu 21
8. awk '$2==20' test.txt
zhangsan 20
9. awk '$2==20 || $1=="lisi"' test.txt
zhangsan 20 lisi 19
10. awk '/w/' test.txt
wangwu 21
11. awk 'NR > 1 {print "name:", $1,"age:", $2}' test.txt
name: lisi age: 19 name: wangwu age: 21
12. awk 'BEGIN {print "Name Age"} {print}' test.txt
Name Age zhangsan 20 lisi 19 wangwu 21
13. awk 'BEGIN {print "Name Age"} $2 > 19 {print} END {print "Count: ", NR}' test.txt
Name Age zhangsan 20 wangwu 21 Count: 3
14. awk 'BEGIN {print "Name Age"} $2 > 19 {print;count=count+1} END {print count}' test.txt
Name Age zhangsan 20 wangwu 21 2
15:awk 'BEGIN {print "Name Age"} $2 > 19 {print;count=count+1} END {if(count > 0) print count ;else print 0}' test.txt
Name Age zhangsan 20 wangwu 21 2
16. awk 'BEGIN {print "Name Age"} $2 > 19 {print;count=count+1} END {if(count < 0) print count ;else print 0}' test.txt
Name Age zhangsan 20 wangwu 21 0
17. awk 'BEGIN {print "Name Age"} $2 > 19 {print;count=count+1} END {if(count > 0) for(i=0;i<count;i++) print i }' test.txt
Name Age zhangsan 20 wangwu 21 0 1
18.