0

How do I print multiple columns using awk '{printf...? With awk '{print... it is easy:

$ printf bar\\t5 | awk '{print $2,"baz",$1}'
5 baz bar

But if I want to format the digit to show a certain number of decimals, the other columns disappear:

$ printf bar\\t5 | awk '{printf "%.3f\n", $2,"baz",$1}'
5.000

I tried putting the printf statement before each column I wanted formatted, but that resulted in a syntax error:

$ printf bar\\t5 | awk '{printf "%.3f\n",$2, printf "%4s\n","baz", $1}'
awk: cmd. line:1: {printf "%.3f\n",$2, printf "%s\n","baz", $1}
awk: cmd. line:1:                      ^ syntax error

or without the printf and just the format string before each column:

$ printf bar\\t5 | awk '{printf "%.3f\n",$2,"%4s\n","baz", $1}'
5.000

How do I get all the columns to appear when using awk '{printf...?

1
  • Copy/paste your shell script into shellcheck.net and fix the issues it tells you about and then post the updated script. Also add the expected output.
    – Ed Morton
    Apr 16 at 14:17
1

The printf command requires all of the format strings to come first, one % per output column, and then you can reference the columns from your input, one , per column:

$ printf bar\\t5 | awk '{printf "%.3f,%4s|%s\n", $2,"baz",$1}'
5.000, baz|bar

You need exactly the same number of output columns to be referenced in your format string as there are input columns after the format string, or you will get an error (in this example, the output format has three columns, while there are only two input columns):

$printf bar\\t5 | awk '{printf "%.3f,%4s|%s\n", $2,"baz"}'
awk: cmd. line:1: (FILENAME=- FNR=1) fatal: not enough arguments to satisfy format string
        `%.3f,%4s|%s
'
                  ^ ran out for this one

The delimiters in the format string are literal, while commas are used after the format string to delineate input columns.

1

You didn't provide the expected output but it sounds like this might be what you're trying to do, i.e. specify a format for 1 output field but use the default formatting for as many others as occur without listing a format for all fields in the printf formatting string:

$ printf 'bar\t5\n' | awk '{print sprintf("%.3f",$2),"baz",$1}'
5.000 baz bar

or:

$ printf 'bar\t5\n' | awk '{$3=$1; $1=sprintf("%.3f",$2); $2="baz"} 1'
5.000 baz bar

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.