A script may process and analyse many datasets, and the results from its calculations will often need presentation, often in tabular form or some aligned output, either for human readability or to be read by some other software.
The UNIX command printf permits formatted output. It is analogous to the C function of the same name. The syntax is
printf "<format string>" <space-separated argument list of variables>
|
The format string may contain text, conversion codes, and interpreted
sequences.
The conversion codes appear in the same order as the arguments they correspond to. A conversion code has the form
%[flag][width][.][precision]code
where the items in brackets are optional.
The interpreted sequences include:
|
| ||||||||||||||||||||||||||||||||||||||||||||||||
If that's computer gobbledygook here are some examples to make it clearer. The result of follows each printf command, unless it is assigned to a variable through the set mechanism. The commentary after the # is neither part of the output nor should it be entered to replicate the examples. Let us start with some integer values.
set int = 1234
set nint = -999
printf "%8i\n" $int # 8-character field, right justified
1234
printf "%-8d%d\n" $int $nint # Two integers, the first left justified
1234 -999
printf "%+8i\n" $int
+1234
printf "%08i\n" $int
00001234
Now we turn to some floating-point examples.
set c = 299972.458
printf "%f %g %e\n" $c $c $c # The three main codes
299972.458000 299972 2.999725e+05
printf "%.2f %.2g %.2e\n" $c $c $c # As before but set a precision
299972.46 3e+05 +3.00e+05
printf "%12.2f %.2G %+.2E\n" $c $c $c # Show the effect of some flags,
299972.46 3.0E+05 +3.00E+05 # a width, and E and G codes
Finally we have some character examples of printf.
set system = Wavelength
set confid = 95
set ndf = m31
set acol = 12
set dp = 2
printf "Confidence limit %d%% in the %s system\n" $confid $system
Confidence limit 95% in the Wavelength system # Simple case, percentage sign
printf "Confidence limit %f.1%% in the %.4s system\n" $confid $system
Confidence limit 95.0% in the Wave system # Truncates to four characters
set heading = `printf "%10s: %s\n%10s: %s\n\n" "system" $system "file" $ndf`
echo $heading # Aligned output, saved to a
system: Wavelength # variable
file: m31
printf "%*s: %s\n%*s: %.*f\n\n" $acol "system" \
$system $acol "confidence" 2 $confid
system: Wavelength # Aligned output with a variable
confidence: 95.00 # width and precision
set heading = "" # Form a heading by appending to
foreach k ( $keywords ) # variable in a loop. Note the
set heading = $heading `printf "%8s " $k` # absence of \n.
end
echo `printf "%s\n" $heading
Note that there are different implementations. While you can check your system's man pages that the desired feature is present, a better way is to experiment on the command line.
C-shell Cookbook