[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
gawk - printf discards field-width when space modifier used
From: |
David C. Rankin |
Subject: |
gawk - printf discards field-width when space modifier used |
Date: |
Sat, 8 Jan 2022 01:04:42 -0600 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.2.1 |
Version:
GNU Awk 5.1.1, API: 3.1 (GNU MPFR 4.1.0-p13, GNU MP 6.2.1)
Copyright (C) 1989, 1991-2021 Free Software Foundation.
Problem:
When using printf with both the space modifier and field-width modifier for
integer conversions with %d, gawk discards the field-width.
Specific code producing the problem:
printf j ? " % 4d%s" : "% 4d%s", rv, (j<cols-1) ? "" : ORS
This is from a simple shell script calling gawk to generate (rows x cols)
random values between two numbers. The full script used was:
#!/bin/sh
rows="${1:-10}"
cols="${2:-10}"
min="${3:-0}"
max="${4:-10000}"
awk -v rows="$rows" -v cols="$cols" -v min="$min" -v max="$max" 'BEGIN {
minval = max
maxval = min
srand(systime())
for (i=0; i<rows; i++)
for (j=0; j<cols; j++) {
rv = rand() * (max - min) + min
if (rv < minval)
minval = rv
if (rv > maxval)
maxval = rv
printf j ? " % 4d%s" : "% 4d%s", rv, (j<cols-1) ? "" : ORS > "file.txt"
}
printf "min: %d\nmax: %d\n", minval, maxval
}'
Run with the default values to produce a 10x10 set of random numbers in
file.txt, the result is:
1367 7362 2586 9128 467 9470 8295 2085 5238 1928
5658 2652 5527 7186 6550 1673 6640 1593 1502 5424
626 675 9768 2499 9257 2432 60 6278 7153 7959
7805 7831 6708 7110 6285 2011 1043 7112 7581 7745
2448 3545 8473 202 8572 1035 2253 7257 4355 1096
1682 4781 2344 5567 9050 5512 5837 4602 9141 6737
9568 2973 5336 7953 7887 764 4140 7339 1920 6316
3226 9611 7985 4853 3722 5866 8133 3795 3079 6658
5025 3298 4411 1328 1696 4740 1159 7499 1810 7463
9938 2950 9804 1171 9052 7699 6753 2680 3311 9405
The space is added by the space modifier, but the field-width is discarded.
Removing the space modifier, the field-width is respected, e.g. the output
being:
2938 3689 2227 1662 7370 6126 4443 1828 3618 9347
1961 8360 2819 4660 4883 7350 6409 3724 1515 4174
7810 3554 1055 1063 9286 3066 72 1891 3108 9379
1907 8978 6766 8849 7350 2830 2795 9534 8067 1310
3587 5381 9685 180 5213 9720 8209 2341 4015 8178
9819 1507 3783 463 7155 2293 5173 8983 1941 3586
8470 3450 9740 1911 4338 3591 5764 3035 7204 5496
7598 4130 9789 3732 9274 7391 5039 9027 9680 1729
6523 7546 7890 786 9406 5975 7172 6966 8772 6618
5932 8723 24 1334 1957 1208 1215 8047 5697 3722
This behavior is contrary to man 3 printf and
https://www.gnu.org/software/gawk/manual/html_node/Format-Modifiers.html
--
David C. Rankin, J.D.,P.E.
- gawk - printf discards field-width when space modifier used,
David C. Rankin <=