cheat.sheets:printf
# printf
# Format and print data
# This command is typically available as a built-in to many shells, such as the
# Bourne shell and the Bourne Again Shell. However, there also exists a GNU
# alternative, sometimes found over at `/usr/bin/printf`.
# Assign the current date (timestamp style) as a shell variable, using the Bash
# builtin, and make it a suitable filename for a Gzip-compressed Tar archive.
printf -v FileName 'Backup_%(%F_%X)T.tgz' -1
# Simple, feature-full, and portable way by which to echo(1) output to STDOUT.
# Here, the current user's username is displayed, followed by a new line.
printf '%s\n' "$USER"
# Using the Bash builtin, this will output one integer per line, from one to
# one million, in a human-readable kind of way, by appropriately
# comma-separating the units.
printf "%'d\n" {1..1000000}
# Getting these results by using the comma is actually also viable in AWK, but
# you'll likely have to jump through a quotation hoop to get access to it.
# Zero-pad a number in order to maintain a width of 3 characters. It's also
# possible to instead provide a `0` in-place of the hash (`#`).
printf '%#.3d\n' 12
# As above, but instead, space-pad the number. Prefix the `3` with a hyphen
# (`-`) to left-align the number, causing the padding to occur on the right.
printf '%3d\n' 12
# Set a field's spacing by using an integer provided as a variable. This is
# incredibly useful when you're dealing with inconsistent field lengths.
printf '%*s\n' $Integer 'Example Field'
tldr:printf
# printf
# Format and print text.
# More information: <https://www.gnu.org/software/coreutils/printf>.
# Print a text message:
printf "%s\n" "Hello world"
# Print an integer in bold blue:
printf "\e[1;34m%.3d\e[0m\n" 42
# Print a float number with the Unicode Euro sign:
printf "\u20AC %.2f\n" 123.4
# Print a text message composed with environment variables:
printf "var1: %s\tvar2: %s\n" "$VAR1" "$VAR2"
# Store a formatted message in a variable (does not work on zsh):
printf -v myvar "This is %s = %d\n" "a year" 2016
$
cheat.sh