Linux awk [-v] {print} 命令

AWK 是一种处理文本文件的语言,是一个强大的文本分析工具。

语法:语法:awk '条件1 {动作 1} 条件 2 {动作 2} …'  文件名

awk是处理文本文件的语言,所以要传入文本数据供其处理(文件逐行读入),文本传入方式由以下几种:

1)通过管道传入

2)文件作为参数传入(语法格式)

1. {print}:输出传入awk的文本数据

语法1:‘{print}’ : 单引号+大括号;输出全部内容

语法2:'{print $1, $2, $num...}' : 输出第1列,第2列,第num列...

语法3:'{print $1 "," $2}' :输出第1列,第2列,中间以逗号隔开

2. 参数 -v var=value :赋值一个用户定义变量(临时变量)

-v 和 print一般结合使用处理文本:

例:在文件a_test.txt中找到 “hello world” 一行将其删除

cat a_test.txt
this is a test file
hello world
1 name
2 id
100 end
# 
# 注意:awk处理的是文本,所以$1和$2是列号
cat a_test.txt | awk -v var1="hello" -v var2="world" '{if((var1!=$1)&&(var2!=$2)) {print}}'          
this is a test file
1 name
2 id
100 end

应用场景:一般在文本格式统一的配置文件中进行需求操作;

例:将路由表文件中,“11 rt-other” 路由表项删除

cat /etc/iproute2/rt_tables
100 rt-static
201 main_subnet
202 default_subnet
1 rt-wan1.1
200 rt-br0
2 rt-wan2.1
11 rt-other
# 
cat /etc/iproute2/rt_tables | awk -v ifname="rt-other" -v id="11" '{if((ifname!=$2)&&(id!=$1)) {print $1 " " $2}}'
100 rt-static
201 main_subnet
202 default_subnet
1 rt-wan1.1
200 rt-br0
2 rt-wan2.1
#
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值