shell编程——awk
创始人
2024-09-25 22:50:39
用法 awk 'BEGIN{ commands } pattern{ commands } END{ commands }' [INPUTFILE…] awk的输出 (1) print item1,item2,…… 各项目之间使用逗号隔开,而输出时则以空白字符分隔; 输出的item可以为字符串或数值、当前记录的字段(如$1)、变量或awk的表达式;数值会先转换为 字符串,然后再输出;print命令后面的item可以省略,此时其功能相当于print $0, 因此,如果想输出空白行,则需要使 用print “ ”;[root@localhost ~]# awk 'BEGIN { print "line one\nline two\nline three"}' line one line two line three [root@localhost ~]# awk 'BEGIN{print "This","is","test"}' This is test [root@localhost ~]# awk -F: '{print $1,$3}' /etc/passwd | head -n 3 root 0 bin 1 daemon 2 [root@localhost ~]# awk -F: '{printf "%-15s %i\n",$1,$3}' /etc/passwd |head -n 3 root 0 bin 1 daemon 2
输出重定向 print items > output-file print items >> output-file print items | command

root@localhost ~]# awk -F: '{printf "%-15s %i\n",$1,$3 > "test1" }' /etc/passwd

[root@localhost ~]# echo "this is" > test.txt [root@localhost ~]# awk 'BEGIN {OFS="#"} {print $1,$2,"a","test"}' test.txt this#is#a#test [root@localhost ~]# awk 'BEGIN{print ENVIRON["PATH"]}' /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin用户自定义变量 awk允许用户自定义自己的变量以便在程序代码中使用,变量名命名规则与大多数编程语言相同,只 能使用字母、数字和下划线,且不能以数字开头。awk变量名称区分字符大小写。 使用赋值语句进行赋值: [root@localhost ~]# awk 'BEGIN{test="hello";print test}' hello 在命令行中使用-v选项赋值: [root@localhost ~]# awk -v test="hello" 'BEGIN {print test}' hello

# awk命令调用脚本

[root@server ~]# awk  -f  test.awk  awk2.txt

```

```bash

# OFS设置输出结果的间隔符为\t

[root@server ~]# awk  -F  ":"  'BEGIN {OFS="\t"} {print $1,$2}'  /etc/passwd

```

```bash

#查看文件中所有空白行的行号

[root@server ~]# awk  '/^$/{print  NR}'  /root/anaconda-ks.cfg

```

 

 

用户自定义变量:
awk允许用户自定义自己的变量以便在程序代码中使用
变量名命名规则与大多数编程语言相同,只能使用字母、数字和下划线,且不能以数字开头
awk变量名称区分字符大小写

[root@server ~l# awk  'BEGIN{test="hello world" ; print test}'#变量定义在BEGIN中

hello world

 

[root@server ~]# awk -v test="hello world" BEGIN'{ print test}'# 变量定义在-V参数后,
hello world

相关内容

热门资讯

未来三年销售目标突破千亿元!京... 上证报中国证券网讯(记者 刘暄)京东与荣耀4月2日签署战略合作协议,明确未来三年荣耀在京东全渠道销售...
我国科研人员发现99个新物种 我国科研人员发现99个昆虫新物种 为青藏高原生物多样性再添新证 4月1日,我国科研人员在国际动物分类...
兴源自动化取得电芯高效测漏设备... 国家知识产权局信息显示,惠州市兴源自动化设备有限公司取得一项名为“一种电芯高效测漏设备”的专利,授权...
量旋科技完成6亿元C+轮融资 ... 本报讯 (记者张敏)4月3日,深圳量旋科技有限公司(以下简称“量旋科技”)宣布完成6亿元C+轮融资。...
李云泽:推动构建与未来产业全生... 上证报中国证券网讯 据金融监管总局4月3日消息,4月1日,金融监管总局举办党委理论学习中心组集体(扩...