欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

linux命令之awk(gawk)

发布时间:2023/12/20 59 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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的主要特性之一是其处理文本文件中数据的能力.他会自动给一行中的每个数据元素分配一个变量.
默认情况下:

$0 代表整个文本行 $1 代表文本行中的第1个数据字段 $2 代表文本行中的第2个数据字段 $n 代表文本行中的第n个数据字段

示例:
data.txt

this is line 1 this is line 2 this is line 3 this is line 4 this is line 5 gawk '{print $1}' data.txt # 输出 this this this this this

如果要读取其他字段分隔符的文件,可以使用-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 x

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

多个命令之间使用分号(;)分割.使用次提示符一次一行输入程序可以不用(>)

echo "my name is wyh" | gawk '{$4="wang"; print $0}' # my name is wang

5) 从文件中读取程序

跟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

{ test ="'s home directory is" print $1 text $6 }

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)的全部内容,希望文章能够帮你解决所遇到的问题。

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