[awk]语法汇总

来源:互联网 发布:手机淘宝怎样创桌面 编辑:程序博客网 时间:2024/06/05 16:44

#################################################

创建时间:201707051800

更新时间:201707180637

#################################################


awk可以把有格式的文件当作数据库来看待,更像是一个简单的数据库引擎:

        默认把空白符当作字段分隔符(FS),回车当作行分隔符(RS);

        从左向右依次把字段命名为$1, $2, ... $NF; 然后用$0代表整行;


----------------------------------------------------------------------------------------------------------------------------------

1. 命令格式:

    awk    [option]    '[pattern]{actions}'  file ...

   pattern: 用于限制action的执行

        空模式:  不限制action

        BEGIN模式: 限制action在读取流之前执行

        END模式:限制action在读取所有流之后执行

        正则模式:限制action在成功匹配正则时执行

        范围模式:限制action在指定的行范围之内执行

    action: 用于指定要执行的命令

        简单的print:输出指定的字段,默认的OFS为空格;

        结构化语句:用{类似c的语句}作为整体当作action,此时有两对花括号;

2. 常用内置变量: 

       awk变量的引用不需要用$

        FS: Filed Separator     ---> OFS

        RS: Row Separator      ---> ORS

        NF: Number of Filed

        NR: Number of Row

3. awk数据属于关联数组

    遍历使用for (i in arr) { ... }

    判断是不是在数组中使用if (i in arr)

    数组中不存在的元素默值为0

4.需要注意的地方

4.1 Long options may be abbreviated, as long as the abbreviation remains unique.
4.2 All arrays in AWK are associative, i.e. indexed by string values.
4.3 To force a variable to be treated as a number, add 0 to it; to force it to be treated as a string, concatenate it with the null string.
4.4 Uninitialized variables have the numeric value 0 and the string value "" (the null, or empty, string).
4.5 String constants in AWK are sequences of characters enclosed between double quotes (").
4.6 Either the pattern may be missing, or the action may be missing, but, of course, not both. If the pattern is missing, the action is executed for every single record of input.  A missing action is equivalent to { print }.
4.7 Multiple statements may be put on one line by separating them with a ";".
4.8 BEGIN and END are two special kinds of patterns which are not tested against the input.
4.9 BEGIN and END patterns cannot have missing action parts.

原创粉丝点击