linux命令之awk(gawk)
生活随笔
收集整理的這篇文章主要介紹了
linux命令之awk(gawk)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- linux程序之awk(gakw)
- gawk基礎
- 1) gawk程序的基本格式
- 2) 從命令行讀取程序腳本
- 3) 使用數據字段變量
- 4) 在程序腳本中使用多個命令
- 5) 從文件中讀取程序
- 6) 在處理數據前后運行腳本
linux程序之awk(gakw)
gawk程序是Unix中的原始awk程序的GNU版本,gawk程序讓流編輯邁上了一個新臺階,他提供了一種編程語言而不只是編輯命令.
gawk可以做的事:
1.定義變量來保存數據
2.使用算術和字符串操作符來處理數據
3.使用結構化編程概念(if-then語句和循環)來為數據處理增加處理邏輯;
通過提取數據文件中的數據元素,將其重新排列格式化,生成格式化報告
gawk基礎
1) gawk程序的基本格式
gawk options program file選項
-F fs 指定行中劃分數據字段的字段分隔符 -f file 從指定的文件中讀取程序 -v var=value 定義gawk程序中一個變量及其默認值 -mf N 指定要處理的數據文件中的最大字段數 -mr N 指定要處理的數據文件中的最大數據行 -W keyword 指定gawk的兼容模式或警告等級2) 從命令行讀取程序腳本
gawk程序腳本用一對花括號來定義.
gawk '{print "hello world!"}' # 輸入后什么都不會輸出,應為沒有指定文件名,如果你輸入一行文本并按下回車,gawk會對這行文本運行一遍程序腳本,進而打印. # hello world!3) 使用數據字段變量
gawk的主要特性之一是其處理文本文件中數據的能力.他會自動給一行中的每個數據元素分配一個變量.
默認情況下:
示例:
data.txt
如果要讀取其他字段分隔符的文件,可以使用-F指定
gawk -F ':' '{print $1,$2}' /etc/passwd# 輸出 root x bin x daemon x adm x lp x sync x shutdown x halt x mail x operator x games x ftp x nobody x systemd-network x dbus x polkitd x sshd x postfix x chrony x ntp x tcpdump x nscd x mysql x4) 在程序腳本中使用多個命令
多個命令之間使用分號(;)分割.使用次提示符一次一行輸入程序可以不用(>)
echo "my name is wyh" | gawk '{$4="wang"; print $0}' # my name is wang5) 從文件中讀取程序
跟sed一樣,gwak編輯器可以允許將程序存儲到文件中,然后再在命令行中引用
scripts.gawk
{print $1 "'s home directory is " $6} gawk -F ':' -f script.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 shutdown's home directory is /sbin halt's home directory is /sbin mail's home directory is /var/spool/mail operator's home directory is /root games's home directory is /usr/games ftp's home directory is /var/ftp nobody's home directory is / systemd-network's home directory is / dbus's home directory is / polkitd's home directory is / sshd's home directory is /var/empty/sshd postfix's home directory is /var/spool/postfix chrony's home directory is /var/lib/chrony ntp's home directory is /etc/ntp tcpdump's home directory is / nscd's home directory is / mysql's home directory is /var/lib/mysql可以在程序文件中指定多條命令,每條命令放一行,不需要分號,否則需要.
在程序中定義變量,賦值即定義,引用直接使用變量名
script3.gawk
6) 在處理數據前后運行腳本
gawk 'BEGIN {print "Start of file"}; {print $0}; END { print "End of file"}' data.txt----------輸出 Start of file this is line 1 this is line 2 this is line 3 this is line 4 this is line 5 End of file總結
以上是生活随笔為你收集整理的linux命令之awk(gawk)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uoj #172. 【WC2016】论战
- 下一篇: mysql 访问被拒绝如何解决