Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

awk - What does a number do after curly braces?

Why does

echo foo bar..baz bork | awk 'BEGIN{RS=".."} {gsub(OFS,"");}1'

seem to do the same thing as

echo foo bar..baz bork | awk 'BEGIN{RS=".."} {gsub(OFS,"");} {print;}'

?

In fact any number that isn't zero (including decimals and negatives) will do the same thing. However, leaving off the digit, using a text character, or using zero prints nothing. I didn't see this documented anywhere, although I could have missed something.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you remember, awk is a language which has a series of <pattern> <action> operations. Each pattern is evaluated for each line (at least conceptually), and when the pattern matches, the action is executed. Either the pattern or the action can be omitted. An omitted pattern matches every line; an omitted action defaults to {print $0} (aka {print}). The 'pattern' might be a simple regex match, or some other more complicated and general condition, which must evaluate to true if the action is to be executed (as noted by Ed Morton in his comment).

In your example, the 1 is a pattern; it evaluates to true. The action is not specified, so the default action is invoked, which is {print} or {print $0}. Any value other than zero or an empty string evaluates to true and will invoke the print. (Note that if you mention an uninitialized variable (for example, c), then it is autocreated and set to zero and therefore evaluates to false. Hence awk 'c' <<<"Hi" prints nothing.)

The actions associated with the BEGIN and END patterns are handled specially, of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...