zoukankan      html  css  js  c++  java
  • linux awk进阶篇

    上一篇主要是awk的进本应用。本节是awk的进阶篇

    ACTION:除去常用的print和printf还有以下几个

    • expression:表达式 如$1>3
    • control statements:控制语句,如if,while等
    • compound statements:组合语句
    • input statements :输入语句
    • output statements:输出语句

    control statements

      if:

        if(condition) statements

        if(condition) statements else statements

        if用法示例

          

          uid>1000为普通用户,否则是root或者系统用户(centos7)

          

      while:

        while(condition) statements

        do statements while(condition)

        while语法示例

          

            while中嵌套if

          

      for:

        for(expr1;expr2;expr3) statement

         expre1,2,3分别为:初始表达式;终止条件;步长表达式

        for示例

          

      swith:

        swith(expression){case value1 or /regxp/:statement;case value2 or /regxp2/:statement……default:statement}

      next:结束对本行数据的处理直接进入下一行

        next示例

             

    数组:array

      关联数组:array[index expression]

        index expression:

          可以使用任意字符串;

          字符串必须用双引号引起来。

          若引用一个数组中不存在的元素。awk会自动创建该元素,并且赋予其初始值——空字符或者数字0

        特殊用法:使用for循环数组以遍历其中元素——for (i in array) body

          array示例:

          

            统计命令中的tcp状态出现次数

          

            不是用BEGIN模式

          

    练习题:

    统计/etc/fstab文件中第三个字段(文件系统)出现的次数

      

    统计/etc/fstab文件中所有单词分别出现的次数

        首先使用for(expre1,expre2,expre3)遍历每行中的每个元素,然后保存在数组ws中。然后使用for(i in ws)遍历数组中的每一个元素。最后输出元素及其出现次数。

      

    函数:内置函数和自定义函数

      内置函数:

        数值处理

          rand():随机生成0~1之间的小数。

        字符串处理

          length([s]):返回指定字符串长度。

          sub(r,s,[t]):将字符串t中第一次被模式r匹配的字符串替换成s。

          gsub(r,s,[t]):将字符串t中所有被模式r匹配的字符串替换成s。

          split(s,a,[r]):以r为分隔符切割字符串s,并将结果保存在数组a中。

            

  • 相关阅读:
    tar命令,vi编辑器
    Linux命令、权限
    Color Transfer between Images code实现
    利用Eclipse使用Java OpenCV(Using OpenCV Java with Eclipse)
    Matrix Factorization SVD 矩阵分解
    ZOJ Problem Set
    Machine Learning
    ZOJ Problem Set
    ZOJ Problem Set
    ZOJ Problem Set
  • 原文地址:https://www.cnblogs.com/wxxjianchi/p/9149862.html
Copyright © 2011-2022 走看看