zoukankan      html  css  js  c++  java
  • linux awk基本语法命令总结

    一、基本用法

    文本内容准备

    2 this is a test
    3 Are you like awk
    This's a test
    10 There are orange,apple,mongo

    用法一:行匹配语句awk ‘'只能使用单引号

    实例:每行按空格或TAB分割,输出文本中的1、4项

    [root@master mnt]# cat log.txt |awk '{print $1,$4}'
    2 a
    3 like
    This's 
    10 orange,apple,mongo
    格式化输出

    [root@master mnt]# cat log.txt |awk '{printf "%-8s %-10s ",$1,$4}'
    2 a
    3 like
    This's
    10 orange,apple,mongo

    用法二:-F,指定分隔符

    [root@master mnt]# cat log.txt |awk -F ',' '{print $1,$2}'
    2 this is a test 
    3 Are you like awk 
    This's a test 
    10 There are orange apple

    或者使用内建表量

    [root@master mnt]# cat log.txt |awk 'BEGIN{FS=","} {print $1,$2}'
    2 this is a test
    3 Are you like awk
    This's a test
    10 There are orange apple

    #使用多个分隔符,先使用空格分割,然后对分割结果再使用“,”分割

    [root@master mnt]# cat log.txt |awk -F '[ ,]' '{print $1,$2,$5}'
    2 this test
    3 Are awk
    This's a
    10 There apple

    用法三:awk -v #设置变量

    [root@master mnt]# cat log.txt |awk -va=1 -vb=s -vc=w '{print $1,$1+a,$1b,$1c}'
    2 3 2s 2w
    3 4 3s 3w
    This's 1 This'ss This'sw
    10 11 10s 10w

    [root@master mnt]# cat log.txt |awk -va=1 '{print $1,$1+a}'
    2 3
    3 4
    This's 1
    10 11

    用法四:awk -f {awk脚本} {文件名}

    过滤第一列大于2的行
    [root@master mnt]# cat log.txt |awk '$1>2' 3 Are you like awk This's a test 10 There are orange,apple,mongo
    过滤第一列等于2的行

    [root@master mnt]# cat log.txt |awk '$1==2 {print $1,$2}'
    2 this

    过滤第一列大于2并且第二列等于'Are'的行

    [root@master mnt]# cat log.txt |awk '$1>2 && $2=="Are" {print $1,$2}'
    3 Are

    用法五:指定输出分割符

    [root@master mnt]# cat log.txt |awk '{print $1,$2,$5}' OFS=";" 
    2;this;test
    3;Are;awk
    This's;a;
    10;There;

    用法六:正则字符串匹配

    输出第二列包含“th” ,并打印第二列与第四列
    [root@master mnt]# cat log.txt  |awk '$2 ~ /th/ {print $2,$4}'
    this a

    ~表示模式匹配。//中是匹配的字符串

    用法七:忽略大小写

    [root@master mnt]# cat log.txt |awk 'BEGIN{IGNORECASE=1} /THIS/ '
    2 this is a test
    This's a test

    用法八:模式取反

    输出第二列不包含"th"的行的第二列和第四列
    [root@master mnt]# cat log.txt |awk '$2 !~ /th/ {print $2,$4}'
    Are like
    a 
    There orange,apple,mongo
    等同于

    [root@master mnt]# cat log.txt |awk '!/th/ {print $2,$4}'
    Are like
    a
    There orange,apple,mongo

  • 相关阅读:
    STM32 Cubemx 输出可调频率与占空比的PWM
    程序员必知的十大基础实用算法及其讲解
    [51单片机]18B20驱动函数
    《嵌入式怎么学?新人十问及解答》
    Google Chrome快捷键大全
    SSD、高级格式化硬盘,4K,分区,对齐,Ghost能不能用的解释用SSD的都可以看看
    资源下载
    Nexus Root Toolkit教程——刷机
    校园卡植入手机教程
    基于Visual c++ 2012的php扩展开发
  • 原文地址:https://www.cnblogs.com/yfb918/p/10677913.html
Copyright © 2011-2022 走看看