Why does “1” in awk print the current line?

后端 未结 3 987
孤独总比滥情好
孤独总比滥情好 2020-11-28 08:58

In this answer,

awk \'$2==\"no\"{$3=\"N/A\"}1\' file

was accepted. Note the 1 at the end of the AWK script. In the comments,

相关标签:
3条回答
  • 2020-11-28 09:03

    In awk,

    Since 1 always evaluates to true, it performs default operation {print $0}, hence prints the current line stored in $0

    So, awk '$2=="no"{$3="N/A"}1' file is equivalent to and shorthand of

    awk '$2=="no"{$3="N/A"} {print $0}' file
    

    Again $0 is default argument to print, so you could also write

    awk '$2=="no"{$3="N/A"} {print}' file
    

    In-fact you could also use any non-zero number or any condition which always evaluates to true in place of 1

    0 讨论(0)
  • 2020-11-28 09:20

    The documentation says

    In an awk rule, either the pattern or the action can be omitted, but not both. If the pattern is omitted, then the action is performed for every input line. If the action is omitted, the default action is to print all lines that match the pattern.

    So, it treats 1 as pattern with no action. The default action is to print the line.

    Even if you have a couple of rules, like in

    awk '
        in_net {
            if (/^\s+bindIp:/) {
                print "  bindIp: 0.0.0.0"
                next
            } else if (/^\s*(#.*)?$/) {
                in_net = 0
            }
        }
        /^net:/ {
            in_net = 1
        }
        1
    ' /etc/mongod.conf
    

    You still need 1, since default action is triggered only when encountering rule with no action.

    0 讨论(0)
  • 2020-11-28 09:21

    AWK works on method of condition and then action. So if any condition is TRUE any action which we mention to happen will be executed then.

    In case of 1 it means we are making that condition TRUE and in this case we are not mentioning any action to happen, so awk's by default action print will happen.

    So this is why we write 1 in shortcut actually speaking.

    0 讨论(0)
提交回复
热议问题