• awk常见基本使用


    -F 指定分割符号

    print 外层的引号必须是单引号 $n不能被解析

    [root@bogon ~]# cat 1.txt 
    a:b:c:d
    a1:b1:c1:d1
    a2:b2:c2:d2
    a_: :c:dddd
    [root@bogon ~]# awk -F ':' '{print $1}' 1.txt 
    a
    a1
    a2
    a_
    [root@bogon ~]# awk -F ':' '{print $2}' 1.txt 
    b
    b1
    b2
    [root@bogon ~]# awk -F ':' '{print $1,$4}' 1.txt 
    a d
    a1 d1
    a2 d2
    a_ dddd

    匹配第三列含有数字的

    awk -F ':' '$3~/[0-9]/' 1.txt

    $0 表示整行
    ~ 模糊匹配
    == 精准匹配
    匹配第三列含有数字只显示第一列和第三列

    awk -F ':' '$3~/[0-9]/ {print $1,$3}' 1.txt 

    重新指定分割符 OFS要放在前面 打印出的不能是$0

    awk -F ':' '$3~/[0-9]/ {OFS="#";print $1,$3}' 1.txt 
    awk -F ':' '$1=="a2"||NR>3 {print $0}' 1.txt

    NR 行号
    NF 被分割后的列数
    ||或者 ,&& 且
    第一段等于a2或者 行号>3的结果

    [root@bogon ~]# awk -F ':' '$3~/[0-9]/' 1.txt 
    a1:b1:c1:d1
    a2:b2:c2:d2
    [root@bogon ~]# awk -F ':' '$3~/[0-9]/ {print $1,$3}'  1.txt 
    a1 c1
    a2 c2
    [root@bogon ~]# awk -F ':' '$3~/[0-9]/ {OFS="#";print $1,$3}' 1.txt 
    a1#c1
    a2#c2

    精准匹配
    字符必须加引号

    awk -F ':' '$1=="a2" {print $0}' 1.txt
    [root@bogon ~]# awk -F ':' '$1=="a2" {print $0}' 1.txt
    a2:b2:c2:d2
    [root@bogon ~]# awk -F ':' '$1=="a2"||NR>3 {print $0}' 1.txt
    a2:b2:c2:d2
    a_: :c:dddd
    表达式 
    [root@bogon ~]# awk -F ':' '$1=$2$3 {print $0}'  1.txt 
    bc b c d
    b1c1 b1 c1 d1
    b2c2 b2 c2 d2
     c   c dddd

    查找分割后 列数 是3到5个的

    awk -F ':' 'NF>=3&&NF<=5 {print}' 1.txt
    [root@bogon ~]# cat 1.txt 
    a:b:c:d
    a1:b1:c1:d1
    e:f
    e1:f1:g1
    e2:f2:g2:h2:i:j:k
    [root@bogon ~]# awk -F ':' 'NF>=3&&NF<=5 {print}' 1.txt 
    a:b:c:d
    a1:b1:c1:d1
    e1:f1:g1
    awk -F ':' '{OFS="#";print $NR,$NF}'  1.txt
    [root@bogon ~]# cat 1.txt 
    a:b:c:d
    a1:b1:c1:d1
    e:f
    e1:f1:g1
    e2:f2:g2:h2:i:j:k
    [root@bogon ~]# awk -F ':' '{OFS="#";print $NR,$NF}'  1.txt
    a#d
    b1#d1
    #f
    #g1
    i#k

    对于以上 $NR,$NF的解析
    1,4
    2,4
    3,2
    4,3
    5,7

  • 相关阅读:
    环境变量
    Python的简介和入门程序
    Mybatis的分页插件PageHelper的使用
    SQLyog 快捷键总结
    如何查看开发项目框架的版本信息
    Linux find命令示例 30
    转:数据库索引原理------MemCached
    array_merge 和 + 的区别
    [介绍]PHP设计模式:DAO(数据访问对象模式)
    PHP业务逻辑层和数据访问层设计
  • 原文地址:https://www.cnblogs.com/HKUI/p/6446114.html
Copyright © 2020-2023  润新知