字符截取命令-awk命令

awk命令是一個異常複雜的命令。瞭解常用的用法。

功能:文件中截取我們需要的數據

#awk '條件1{動作1}條件2{動作2}...' 文件名

說明:

條件(Pattern)
- 一般使用關係表達式作爲條件
- x>10判斷變量 x是否大於10
- x>=10 大於等於10
- x<=10 小於等於10
動作(Action)
- 格式化輸出
- 流程控制語句

例如:

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70

查看文件student.txt第二列和第四列

[root@localhost home]# awk '{printf $2 "\t" $4 "\n"}' student.txt 
Name    Mark
furong  88
fengjie 60
cang    70

說明

  • awk一行一行的的讀取文件
  • 判斷條件,如果條件滿足,則執行動作
  • 把文件名賦值給$0字段,將ID賦值給$1字段,依次類推
  • awk默認是空格或者製表符做爲分隔符
  • 沒有條件限制就是無條件顯示執行動作
  • 僅僅是提取製表符和有規律的

示例:

[root@localhost home]# df -h | awk '{print $5}'
Use%
21%
0%
30%
1%
1%
[root@localhost home]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda6       5.9G  1.2G  4.5G  21% /
tmpfs           491M     0  491M   0% /dev/shm
/dev/sda1       190M   54M  127M  30% /boot
/dev/sda2       9.5G   23M  9.0G   1% /home
/dev/sda5       1.9G  3.1M  1.8G   1% /usr/local
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $%}'
awk: {print $%}
awk:         ^ syntax error
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $5}'
21%
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $5}' | cut -d "%" -f 1
21

示例2

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# awk 'BEGIN{print "this is a test"}{print $2 "\t" $4}' student.txt 
this is a test
Name    Mark
furong  88
fengjie 60
cang    70
[root@localhost home]# awk 'END{print "this is a test"}{print $2 "\t" $4}' student.txt 
Name    Mark
furong  88
fengjie 60
cang    70
this is a test

BEGIN作用,awk默認是用空格或者製表符進行分割的。BEGIN作用是設定變量來做分隔符。如果不寫BEGIN,則awk會從讀取第一行後才能執行按照分隔符分割的。

[root@localhost home]# cat /etc/passwd |grep "/bin/bash"
root:x:0:0:root:/root:/bin/bash
imooc:x:502:889:kk,kk,kk,kk:/home/xxx:/bin/bash
cls:x:500:889:dgdzmx:/home/cls:/bin/bash
user1:x:503:503::/home/user1:/bin/bash
tony:x:504:504::/home/tony:/bin/bash
lw:x:505:505::/home/lw:/bin/bash
user2:x:506:506::/home/user2:/bin/bash
[root@localhost home]# cat /etc/passwd |grep "/bin/bash" | awk 'BEGIN{FS=":"}{printf $1 "\t" $3}'
root    0imooc  502cls  500user1    503tony 504lw   505user2    506[root@localhost home]# cat /etc/passwd |grep "/bin/bash" | awk 'BEGIN{FS=":"}{printf $1 "\t" $3 "\n"}'
root    0
imooc   502
cls 500
user1   503
tony    504
lw  505
user2   506
[root@localhost home]# cat /etc/passwd |grep "/bin/bash" |grep -v "root" |  awk 'BEGIN{FS=":"}{printf $1 "\t" $3 "\n"}'
imooc   502
cls 500
user1   503
tony    504
lw  505
user2   506
[root@localhost home]# 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章