十五、gawk命令使用
gawk命令
gawk程序是Unix中原始awk程序的GNU版本。
它可以用來寫腳本的方式處理文本數據。
他可以
定義變量保存數據
使用算數運算符字符串操作符處理數據
使用結構化邏輯語句處理數據
提取數據重新定義格式(如過濾日志文件找出錯誤行便于集中處理閱讀)
語法格式
gawk options program file
gawk選項
| 選項 | 描述 |
| -F fs | 指定分隔符 |
| -f file | 指定含有命令的文件 |
| -v var=value | 定義變量 |
| -mf N | 指定處理文件中最大字段數 |
| -mr N | 指定數據文件中最大數據行數 |
| -W keyword | 指定gawk的兼容模式或警告等級 |
從命令行讀取程序腳本
gawk命令的腳本使用花括號定義。
gawk命令認為腳本是一串字符串所以還需要用單引號括起來。
gawk程序會針對數據流中的每行文本執行程序腳本。
注意:如下命令,因為沒有在命令行上指定文件名,gawk默認會從STDIN也就是鍵盤接收數據。
即從鍵盤中中隨便輸入文本,接著都會執行輸出Hello World!然后再等待輸入。
[root@tzPC 19Unit]# gawk '{print "Hello World!"}'
This is a test
Hello World!
Ctrl+D可以終止gawk程序
使用數據字段變量
gawk會自動給一行中每個數據字段分配一個變量
$0代表整個文本行
$1代表文本行中的第1個數據字段
$2代表文本行中第2個數據字段
...
在文本行中每個數據字段都是通過字段分隔符劃分的。默認是空格或制表符
例:使用gawk讀取文本文件,顯示第一個數據字段的值
[root@tzPC 19Unit]# cat data2.txt
One line of test text.
Two lines of test text.
Three lines of test text.
[root@tzPC 19Unit]# gawk '{print $1}' data2.txt
One
Two
Three
-F參數更改字段分隔符
[root@tzPC 19Unit]# gawk -F: '{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
...
在程序腳本中使用多個命令
使用分號分隔命令即可。
[root@tzPC 19Unit]# echo "My name is tz" | gawk '{$4="root";print $0}'
My name is root
也可以使用如下寫法
因為沒有輸入數據流,所以gawk默認會從STDIN中獲取數據也就是從鍵盤中獲取,所以要手動輸入數據,然后才會執行gawk命令輸出數據,使用Ctrl+D退出程序
[root@tzPC ~]# gawk '{
> $4="root"
> print $0}'
My name is tz
My name is root
從文件中讀取程序命令
使用-f選項指定命令文件
[root@tzPC 19Unit]# cat script2.gawk
{print $1 "'s home directory is " $6}
[root@tzPC 19Unit]# gawk -F: -f script2.gawk /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
...
使用含有多行命令的命令文件
注意:這里定義了變量text,再次調用它的時候不需要加$
[root@tzPC 19Unit]# cat script3.gawk
{
text="'s home directory is "
print $1 text $6
}
[root@tzPC 19Unit]# gawk -F: -f script3.gawk /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
sync's home directory is /sbin
在處理數據前運行腳本
使用關鍵字BEGIN
[root@tzPC 19Unit]# cat data3.txt
Line 1
Line 2
Line 3
[root@tzPC 19Unit]# gawk 'BEGIN {print "The data3 File Contents:"}
> {print $0}' data3.txt
The data3 File Contents:
Line 1
Line 2
Line 3
再處理數據后運行腳本
使用END關鍵字
[root@tzPC 19Unit]# gawk 'BEGIN {Print "The data3 File Contents:"}
> {print $0}
> END {print "End of File"}' data3.txt
Line 1
Line 2
Line 3
End of File
高大上的格式化輸出報告用法來了,圈重點!
[root@tzPC 19Unit]# cat script4.gawk
BEGIN{
print "The latest list of users and shells"
print " UserID Shell"
print "------- -------"
FS=":"
}
{
print $1 " " $7
}
END{
print "This concludes the listing"
}
[root@tzPC 19Unit]# gawk -f script4.gawk /etc/passwd
The latest list of users and shells
UserID Shell
------- -------
root /bin/bash
bin /sbin/nologin
postfix /sbin/nologin
sshd /sbin/nologin
tz /bin/bash
This concludes the listing
學習來自:《Linux命令行與Shell腳本大全 第3版》第19章
今天的學習是為了以后的工作更加的輕松!
總結
以上是生活随笔為你收集整理的十五、gawk命令使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: KDE常用桌面插件总结
- 下一篇: 设计模式-行为模式(读书笔记)