4

For my understanding, usually awk follows a file or an output.

Then it will exec its code on everyline of that file or output.

In my case, my command awk '{print "Hi, Judy"}' didn't follow by any file or output.

To my understanding, it should print out nothing or raise up an error.

But why in reality, it pomps out an interactive command line in which if I keep on pressing Enter, it will show me something infinitely like:

Hi, Judy

Hi, Judy

Hi, Judy

Why this command works like that?

# content below this dividing line should be ignored


Addtional Question:

I tried another command:

awk ' BEGIN { print "Hi." }  { print "Buddy." } { print "Bye." } '

I'm expecting it will print Hi. Buddy. Bye. Infinitely.

But I got:

Hi.

Buddy
Bye.

Buddy
Bye.

Buddy
Bye.

Which confusing me again. Why the END clause works infinitely, meanwhile BEGIN clause only works once here?

  • It has to work that way, how else would you use awk in a pipeline, which is the most common usage? Such as sort myfile | awk '{ print $2 }' or something similar? – orion Feb 5 '15 at 12:28
4

It's reading from stdin, i.e. your keyboard.

Try this to see what I mean

awk '{ print "Here is your line:", $0 }'
  • So if awk follows by nothing, it will reads standard-input, is it right? – Zen Feb 5 '15 at 10:56
  • 1
    Exactly - it's perfect for using in a pipeline, most core utilities read from stdin if no file is given for input. – orion Feb 5 '15 at 12:26
  • @roaima, I've updated my question, do you know the reason for the extra question? – Zen Feb 5 '15 at 14:16
  • 3
    @Zen Your code is incorrect: there is no END clause in it, otherwise it would be printed once, like the BEGIN block, but at the end of your data stream. Here is a little bit more information about awk. (by the way, please avoid asking several questions in one ; this doesn't really fit in this community's format ;)) – John WH Smith Feb 5 '15 at 14:21
  • @JohnWHSmith, yes, I made a terrible mistake here. – Zen Feb 5 '15 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.