1

Why does

awk '{print 3 + 3}'

not work, but:

echo 3|awk '{print $1 + 3}'

does?

Couldn't the first statement just output 6? What is the easiest way of printing the result of a calculation?

1

3 Answers 3

6

AWK statements consist of a pattern and an action: quoting the GNU awk manual

a rule is executed when its pattern matches the current input record

In the first case, you are not providing any input record - so you get no action. In this case, you could use the special pattern BEGIN

awk 'BEGIN {print 3 + 3}'
1
  • 1
    You could also just hit "Enter" again after typing in awk '{print 3 + 3}'.
    – Wildcard
    Mar 9, 2016 at 5:13
-1

Equally well you could do

awk 'END {print 3 + 3}'
1
  • This is not "equally" good as steeldriver's answer.  When the only action statements in an awk script are associated with the BEGIN pseudo-pattern, the script runs immediately, without looking at its input.  With your answer, awk reads (and ignores/discards) its input until it reaches EOF, and only then executes the statement. Apr 23, 2016 at 5:54
-2

With bash echo $(( 3 + 3)) or with bc

6
  • Asked specifically for awk. Mar 8, 2016 at 15:36
  • I asked specifically for awk. Mar 8, 2016 at 18:44
  • so? it doesn't always matter what you specifically ask for. When you are asking a wrong question (such as using the wrong or even sub-optimal tool for a job), a good answer will inform you of that fact. "Q. how do i shoot myself in the foot with a banana?" A. "You don't, you use a gun. Better yet, it's a good idea to avoid shooting yourself in the foot, you should do X instead."....and a lot of wrong questions are the OP metaphorically shooting themselves in the foot.
    – cas
    Mar 8, 2016 at 22:59
  • 1
    Unless the OP is actually trying to learn something about Awk...
    – jasonwryan
    Mar 9, 2016 at 5:17
  • @cas: Unless I am actually trying to learn something about Awk... But, yes, you are right that sometimes it is OK to question the OP's assumptions and intentions. In this case, however, awk is a perfectly capable tool. Mar 9, 2016 at 14:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .