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

相关推荐
平头哥技术团队3 分钟前
Day 21 _ 页内锚点_给每段起个 id,目录写 href=_#id_,点一下页面就滚到那一段
前端·html·html5
子兮曰1 小时前
Bun v1.4.1 深度解析:从 Zig 到 Rust,一场 11 天、64 个 AI 代理的语言迁徙
前端·后端·bun
两点王爷1 小时前
解决 Linux 中 version `CXXABI_1.3.8‘ not found 报错
linux·运维·服务器
xx~t1 小时前
嵌入式——51单片机1
linux·c语言·单片机·嵌入式硬件·51单片机
啦啦啦啦啦zzzz1 小时前
利用RAII机制进行日志的采集
linux·服务器·c++·网络编程·c++20
人民广场吃泡面1 小时前
什么是AI Agent?它又能给前端带来哪些效率提升?
前端·人工智能
0+1111 小时前
Linux --线程概念与控制
linux·运维·服务器·jvm
Yang96112 小时前
鼎讯信通DXB-2000S OTDR光时域反射仪模块技术拆解:0.8m盲区
网络
中科三方2 小时前
两家域名注册商资质被ICANN终止:企业域名资产安全再受关注
前端·网络·安全·域名
超智算科技2 小时前
2026服贸会现场直击|Net Zero Hub净零算力枢纽全球首发! 超智算受邀深度参与服贸会全球OPC共创节
网络·人工智能·科技·物联网·gpu算力