Linux Platform

printf

Formater et afficher du texte

affichageformatagetextescript

Syntaxe

printf FORMAT [ARGUMENTS...]

Options principales

OptionDescription
%sFormater en chaine de caractères
%dFormater en nombre entier decimal
%fFormater en nombre a virgule flottante
\nInserer un saut de ligne

Exemples

Afficher un tableau formate

$ printf "%-15s %5s %10s\n" "SERVICE" "PID" "MEMOIRE"
$ printf "%-15s %5d %9.1f%%\n" "nginx" 1234 2.3 "postgres" 5678 15.7 "redis" 9012 4.1
SERVICE           PID    MEMOIRE
nginx              1234       2.3%
postgres           5678      15.7%
redis              9012       4.1%

Generer une ligne de séparation

$ printf '%0.s-' {1..40}; printf '\n'
----------------------------------------

Formater des variables dans un script

$ DISQUE="sda1"; USAGE=78; TOTAL=500
$ printf "Disque /dev/%s : %d%% utilisé (%d Go total)\n" "$DISQUE" "$USAGE" "$TOTAL"
Disque /dev/sda1 : 78% utilisé (500 Go total)