1

I am practicing printf functions with awk command.

echo "unix" | awk '{printf "%5s\n", "hi"}'
awk '{printf "%20s\n", "hi"}'

The first command with echo prints " hi". However, the second command causing a problem. Its output keeps continuing. How do I fix this problem so that it does exactly what the first command does.

3

awk loops on each record of input. If no input files are specified, it uses standard input. If you want to run an expression without using any input, use a BEGIN block, and keep nothing outside it:

$ awk 'BEGIN {print "foo"}'
foo

So, in your case:

awk 'BEGIN {printf "%20s\n", "hi"}'

Usually, the BEGIN block is run before any input is read. So, it is run whether or not there is any input, and since there are no other expressions to run, awk simply exits.

You can also use exit to make awk exit the loop:

awk '{printf "%20s\n", "hi"; exit}'

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.