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 ![](https://i-blog.csdnimg.cn/direct/817882a991aa4567a401e670d8e9160d.png) \[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 > \`\`\` ![](https://i-blog.csdnimg.cn/direct/6951668063c445bd93d76320ec9c81b0.png) ![](https://i-blog.csdnimg.cn/direct/426b910dc42f42c392c81f4e16b33d14.png) ![](https://i-blog.csdnimg.cn/direct/30910bacf18249aa9840ab19b3b35545.png) ![](https://i-blog.csdnimg.cn/direct/7e16c0cd341f4e3c8e65713b452876af.png) 用户自定义变量: 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

相关推荐
葵花日记8 分钟前
LINUX--编译器gcc/g++
linux·运维·服务器
云深麋鹿9 分钟前
数据链路层总结
java·网络
洛小豆26 分钟前
Git 打标签完全指南:从本地创建到远端推送
前端·git·github
威斯软科的老司机34 分钟前
WebSocket压缩传输优化:机器视觉高清流在DCS中的低延迟方案
网络·websocket·网络协议
世间小小鱼34 分钟前
【爬坑指南】亚马逊文件中心 AWS S3 预签名URL 前端直传
前端·云计算·aws
TG_yunshuguoji35 分钟前
亚马逊云代理商:AWS亚马逊云的独特优势与实用价值
服务器·云计算·aws
华仔啊43 分钟前
前端登录token到底应该存在哪?LocalStorage、SessionStorage还是Cookie?一篇说透!
前端·javascript
BeefyBytes1 小时前
动态组件库建设
前端
光路科技1 小时前
光路科技将携工控四大产品亮相工博会,展示工业自动化新成果
运维·科技·自动化
csdn_aspnet1 小时前
Linux Node.js 安装及环境配置详细教程
linux·node.js