shell编程——awk

用法
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

相关推荐
lingllllove4 分钟前
使用 HTTP::Server::Simple 实现轻量级 HTTP 服务器
服务器·网络协议·http
dal118网工任子仪9 分钟前
94,【2】buuctf web [安洵杯 2019]easy_serialize_php
android·前端·php
Linux运维老纪26 分钟前
K8s之Service详解(Detailed Explanation of K8s Service)
服务器·网络·云原生·容器·kubernetes·云计算·运维开发
大模型铲屎官39 分钟前
HTML5 技术深度解读:本地存储与地理定位的最佳实践
前端·html·html5·本地存储·localstorage·地理定位·geolocation api
程序猿编码1 小时前
自定义命令执行器:C++中命令封装的深度探索(C/C++实现)
linux·c语言·c++·网络安全·shell·命令行
一只码代码的章鱼1 小时前
计算机网络 笔记 传输层
网络·网络协议·tcp/ip·计算机网络
一 乐1 小时前
基于vue船运物流管理系统设计与实现(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端·船运系统
别致的影分身2 小时前
Linux网络 HTTP cookie 与 session
网络·网络协议·http
m0_528723812 小时前
在React中使用redux
前端·javascript·react.js