zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    485串口接线
    mvc3 升级mvc5
    VB连接ACCESS数据库,使用 LIKE 通配符问题
    VB6 读写西门子PLC
    可用的 .net core 支持 RSA 私钥加密工具类
    解决 Win7 远程桌面 已停止工作的问题
    解决 WinForm 重写 CreateParams 隐藏窗口以后的显示问题
    解决安装 .net framework 发生 extracting files error 问题
    CentOS7 安装配置笔记
    通过特殊处理 Resize 事件解决 WinForm 加载时闪烁问题的一个方法
  • 原文地址:https://www.cnblogs.com/HKUI/p/6446114.html
Copyright © 2011-2022 走看看