Explain awk command

后端 未结 5 504
谎友^
谎友^ 2020-11-28 06:29

Today I was searching for a command online to print next two lines after a pattern and I came across an awk command which I\'m unable to understand.

$ /usr/x         


        
5条回答
  •  臣服心动
    2020-11-28 06:47

    Explanation

    awk expressions have the following form:

    condition action; NEXT_EXPRESSION
    

    If conditon is true action(s) will be executed. Further note, if condition is true but action has been omitted awk will execute print (the default action).

    You have two expressions in your code that will get executed on every line of input:

    _&&_--          ;
    /PATTERN/{_=2}
    

    Both are separated by a ;. As I told that default action print will happen if the action is omitted it is the same as:

    _&&_--    {print};
    /PATTERN/ {_=2}
    

    In your example _ is a variable name, which gets initialized by 0 on the first line of input, before it's first usage - automatically by awk.

    First condition would be (0) && (0).. What results in the condition being false, as 0 && 0 evaluates to false and awk will not print.

    If the pattern is found, _ will be set to 2 which makes the first condition being (2) && (2) on the next line and (1) && (1) on the next line after that line as _ is decremented after the condition has being evaluated. Both are evaluating to true and awk will print those lines.

    However, nice puzzle ;)

提交回复
热议问题