Cristofer Fuentes
Cristofer Fuentes

Reputation: 441

How to use var inside awk printf

Hi I have something like this in my bash script

gawk '{ printf "%s %s", $1, $2 }' test.txt

Normaly I can limit the lenght of the strings with a number before the s like this:

# Limit strings to 10 characters
gawk '{ printf "%10s %10s", $1, $2 }' test.txt

How I can use a var for that limit ? I get the width of the current terminal with tput cols and I want to set dinamically the lenght of the strings.

Upvotes: 0

Views: 115

Answers (2)

Shawn
Shawn

Reputation: 52344

You can use * in the format specifier to get the width from an argument to printf:

$ gawk -v width=10 '{ printf "%*s %*s\n", width, $1, width, $2 }' <<<"a b"                 
         a          b
$ gawk -v width=3 '{ printf "%*s %*s\n", width, $1, width, $2 }' <<<"a b"
  a   b

This also works with the precision argument (The number after a . in the format).

Upvotes: 2

Cole Tierney
Cole Tierney

Reputation: 10314

One way is to break up your format string and insert the variable.

awk -v w=10 '{printf "%."w"f %."w"f", $1, $2}' <<< '1.2 3.5'
1.2000000000 3.5000000000

awk -v w=3 '{printf "%."w"f %."w"f", $1, $2}' <<< '1.2 3.5'
1.200 3.500

Upvotes: 2

Related Questions