开发者

where to put brackets in awk

Hello every one I want to ask that I am very very confused about the brackets {} in awk like I have written a code

{
   FNR == 3 { print $1 " age is " $2 }
}

but it gave me error on outer brackets but didn't give error on the brackets around the print statement why is it so :/ also in t开发者_如何学运维he following code

{
 s = $1
 d = $2
 no = $1 + $2
 {print no}
}

when I remove outer brackets my arguments displayed, the number of LOC times why is it I am very confuse kindly help me thanks


An awk script consists of commands. Each command has a pattern and an action:

pattern1 { action1 }
pattern2 { action2 }

For each line in the input, awk tests each pattern and performs the corresponding action when the pattern is true.

The pattern can be omitted, in which case it is taken as always true and the action is performed for each line. Similarly, the action can be omitted, in which case it is taken as a print; this lets you easily use awk to select lines without changing the lines.

With this structure in mind, we can interpret the given examples. The first one is a single action that is applied to every line. But the action isn't well formed---if you remove the outer brackets, it becomes a distinct pattern and action, both of which are correctly constructed.

The second example also is applied to every line. It takes the first two (whitespace separated) fields from the lines, adds them as numbers, and prints the result. Removing the outer brackets gives you three patterns without corresponding actions, and an action without a pattern. Thus, the patterns---which are the value of the assignments, and usually true---have an implicit print that is usually invoked. Similarly, the action is always invoked, printing the value of no.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜