欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

shell基础09 gawk程序(上)

发布时间:2024/8/26 55 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 Code

3. 使用数据字段变量

    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 Code

4. 在程序脚本中使用多个命令

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 Code

6. 在数据处理前/后运行脚本

    希望在读取数据前处理一些语句或者读取后处理一些语句,可以使用关键字BENGIN和END.

 

参考文献

Linux命令行与shell脚本编程大全(第3版)[美] 布鲁姆(Richard Blum),布雷斯纳汉(Christine Bresnahan) 著,门佳,武海峰 译

转载于:https://www.cnblogs.com/Hermioner/p/9411565.html

总结

以上是生活随笔为你收集整理的shell基础09 gawk程序(上)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。