Mastering Linux printf: Formatting and Data Output Techniques
Learn how the Linux printf command mimics C's printf function to format and output text, understand its syntax and options, and explore practical examples ranging from simple string printing to complex formatted tables using format specifiers and custom scripts.
printf: Format and Print Data
Function Description
printf command imitates the C language printf() function.
The purpose of printf is to output text according to a specified format. Unlike echo, printf does not automatically add a newline; you must add \n manually.
Command Syntax
printf [options] [text1] [text2] ...Option Meanings
\a: alert character, usually the ASCII BEL character \n: newline \r: carriage return \0ddd: represents a character with 1‑3 digit octal value \ddd: represents a character with 1‑3 digit octal value, valid only in format strings
Reference Examples
(1) String output:
# printf "Hello, World
"
Hello, World(2) Using format specifier "%s" for output:
# printf "%s
" a b c d
a
b
c
d
# printf "%s %s
" a b c d
a b
c d
# printf "%s %s %s
" a b c d e f
a b c
d e f(3) Script demonstrating printf's power:
# vim printf.sh
printf "%-10s %-8s %-4s
" Name Gender Weightkg
printf "%-10s %-8s %-4.2f
" ZhangSan Male 59.5278
printf "%-10s %-8s %-4.2f
" LiSi Male 62.7323
printf "%-10s %-8s %-4.2f
" WangWu Female 49.8767Execution result:
# sh printf.sh
Name Gender Weightkg
ZhangSan Male 59.53
LiSi Male 62.73
WangWu Female 49.88%s %c %d %f are format specifiers. %-10s specifies a field width of 10 characters; “-” left‑aligns, otherwise right‑aligns, padding with spaces if needed. %-4.2f formats a floating‑point number with two decimal places.
(4) Adding parentheses around a,b,c,d:
# printf "( %s )" a b c d; echo ""
( a )( b )( c )( d )Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
