shell基础09 gawk程序(上)
生活随笔
收集整理的這篇文章主要介紹了
shell基础09 gawk程序(上)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ?gawk提供了一種編程語言而不知識編輯器命令。
1. 命令格式
? ? ?gawk? options? program file
2. 從命令行讀取程序腳本
? ? ?默認是從STDIN讀取,也可以指定從文件中讀取? ??
1 [Hermioner@localhost Documents]$ gawk '{print "Hello world"}' 2 a #從鍵盤輸入的a 3 Hello world 4 b #從鍵盤輸入的b 5 Hello world #按住ctrl+d才可以結束 6 [Hermioner@localhost Documents]$ View Code3. 使用數據字段變量
? ? gawk會將每行的數據分配成對應的變量。默認的分隔符是空白字符(空格或者tab等),可以指定分隔符。
? ?$0代表整個文本行;
? ?$1代表文本行中的第一個數據字段,以此類推。
1 [Hermioner@localhost Documents]$ cat data.txt 2 this is one line. 3 this is two line. 4 this is three line. 5 [Hermioner@localhost Documents]$ gawk '{print $1}' data.txt 6 this 7 this 8 this 9 [Hermioner@localhost Documents]$ gawk '{print $2}' data.txt 10 is 11 is 12 is 13 [Hermioner@localhost Documents]$ gawk '{print $3}' data.txt 14 one 15 two 16 three 17 [Hermioner@localhost Documents]$ gawk '{print $4}' data.txt 18 line. 19 line. 20 line. 21 [Hermioner@localhost Documents]$ gawk '{print $5}' data.txt View Code4. 在程序腳本中使用多個命令
1 [Hermioner@localhost Documents]$ echo "My name is Rich" | gawk '{$4="Tom";print $0}' 2 My name is Tom 3 [Hermioner@localhost Documents]$ View Code? ? 多條命令之間用分號隔開就可以了。
5.? 從文件中讀取程序
? ? ?比如冒號為分隔符,讀取passwd中的數據
1 [Hermioner@localhost Documents]$ cat script.gawk 2 {print $1 "'s home directory is " $6} 3 4 [Hermioner@localhost Documents]$ gawk -F: -f script.gawk /etc/passwd 5 root's home directory is /root 6 bin's home directory is /bin 7 daemon's home directory is /sbin View Code6. 在數據處理前/后運行腳本
? ? 希望在讀取數據前處理一些語句或者讀取后處理一些語句,可以使用關鍵字BENGIN和END.
?
參考文獻:
Linux命令行與shell腳本編程大全(第3版)[美]?布魯姆(Richard Blum),布雷斯納漢(Christine Bresnahan) 著,門佳,武海峰?譯
轉載于:https://www.cnblogs.com/Hermioner/p/9411565.html
總結
以上是生活随笔為你收集整理的shell基础09 gawk程序(上)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 的overcommit_me
- 下一篇: 关于async 中return 和 re