曾有人推測 awk 命令的名字來源于 awkward 這個單詞。其實不然,此命令的設計者有 3 位,他們的姓分別是 Aho、Weingberger 和 Kernighan,awk 就取自這 3 為大師姓的首字母。
和 sed 命令類似,awk 命令也是逐行掃描文件(從第 1 行到最后一行),尋找含有目標文本的行,如果匹配成功,則會在該行上執行用戶想要的操作;反之,則不對行做任何處理。[root@localhost ~]# awk [選項] '腳本命令' 文件名
此命令常用的選項以及各自的含義,如表 1 所示。| 選項 | 含義 |
|---|---|
| -F fs | 指定以 fs 作為輸入行的分隔符,awk 命令默認分隔符為空格或制表符。 |
| -f file | 從腳本文件中讀取 awk 腳本指令,以取代直接在命令行中輸入指令。 |
| -v var=val | 在執行處理過程之前,設置一個變量 var,并給其設備初始值為 val。 |
'匹配規則{執行命令}'
這里的匹配規則,和 sed 命令中的 address 部分作用相同,用來指定腳本命令可以作用到文本內容中的具體行,可以使用字符串(比如 /demo/,表示查看含有 demo 字符串的行)或者正則表達式指定。另外需要注意的是,整個腳本命令是用單引號('')括起,而其中的執行命令部分需要用大括號({})括起來。在 awk 程序執行時,如果沒有指定執行命令,則默認會把匹配的行輸出;如果不指定匹配規則,則默認匹配文本中所有的行。
舉個簡單的例子:[root@localhost ~]# awk '/^$/ {print "Blank line"}' test.txt
在此命令中,/^$/ 是一個正則表達式,功能是匹配文本中的空白行,同時可以看到,執行命令使用的是 print 命令,此命令經常會使用,它的作用很簡單,就是將指定的文本進行輸出。因此,整個命令的功能是,如果 test.txt 有 N 個空白行,那么執行此命令會輸出 N 個 Blank line。[root@localhost ~]# cat data2.txt
One line of test text.
Two lines of test text.
Three lines of test text.
[root@localhost ~]# awk '{print $1}' data2.txt
One
Two
Three
[root@localhost ~]# echo "My name is Rich" | awk '{$4="Christine"; print $0}'
My name is Christine
[root@localhost ~]# awk '{
> $4="Christine"
> print $0}'
My name is Rich
My name is Christine
注意,此例中因為沒有在命令行中指定文件名,awk 程序需要用戶輸入獲得數據,因此當運行這個程序的時候,它會一直等著用戶輸入文本,此時如果要退出程序,只需按下 Ctrl+D 組合鍵即可。
[root@localhost ~]# cat awk.sh
{print $1 "'s home directory is " $6}
[root@localhost ~]# awk -F: -f awk.sh /etc/passwd
root's home directory is /root
bin's home directory is /bin
daemon's home directory is /sbin
adm's home directory is /var/adm
lp's home directory is /var/spool/lpd
...
Christine's home directory is /home/Christine
Samantha's home directory is /home/Samantha
Timothy's home directory is /home/Timothy
[root@localhost ~]# cat data3.txt
Line 1
Line 2
Line 3
[root@localhost ~]# awk 'BEGIN {print "The data3 File Contents:"}
> {print $0}' data3.txt
The data3 File Contents:
Line 1
Line 2
Line 3
[root@localhost ~]# awk 'BEGIN {print "The data3 File Contents:"}
> {print $0}
> END {print "End of File"}' data3.txt
The data3 File Contents:
Line 1
Line 2
Line 3
End of File
本節僅介紹了 awk 程序的基本用法,更高級的用法會在下節繼續介紹。
新聞熱點
疑難解答