|


| NAVIGATION |
|
Home |
|
Store |
|
|
| INSIDE MAC |
|
Television Shows |
|
Broadcast Shows |
|
Daily News Shows |
|
Special Shows |
|
|
| EVENTS |
|
|
|
|
|
|
|
|
| DAILY TIPS |
|
Design |
|
Mac OS X |
|
Mac OS X UNIX |
|
|
| COMMUNITY |
|
Forums |
|
Surveys |
|
|
| NEWS |
|
Current |
|
Press |
|
Archive |
|
|
| FEATURES |
|
Editorial |
|
Dr. Mac |
|
Reviews |
|
Reader Reports |
|
|
| RESOURCES |
|
FAQ |
|
Documentation |
|
Learning Center |
|
MAN pages |
|
Glossary |
|
Tutorials |
|
Tips |
|
Links |
|
|
|

|
|
|
OSXFAQ Mac OS X UNIX Tip-of-the-Day
Scripting One-Liners - Fancy Printing
Ever wanted to spice up the output from a script, like aligning numbers or zero padding them. Then consider using 'printf' over echo.
Here's how to print numbers in columns, right justified.
$ num1=4; num2="123"
$ printf "Value: %5d units\n" $num1; printf "Value: %5d units\n" $num2
Value: 4 units
Value: 123 units
Printf prints what's inside its format string. %5d tells printf to look outside the format string and interpret what it finds as a decimal number and to write it to a column 5 characters wide.
And to left justify:
$ printf "Value: %-5d units\n" $num1; printf "Value: %-5d units\n" $num2
Value: 4 units
Value: 123 units
And to print leading zeros:
$ printf "Value: %05d units\n" $num1; printf "Value: %05d units\n" $num2
Value: 00004 units
Value: 00123 units
You can also change the format stored in a variable:
$ num1=$(printf "%05d" $num1)
$ echo $num1
00004
The printf function can do much than than shown here. It uses the printf library function, which is documented by:
$ man 3 printf
|





|
 |
|
 |
Copyright © 2000-2008 Inside Mac Media, Inc. All rights reserved. |
Apple assumes no responsibility with regard to the selection, performance, or use of the products or services. All understandings, agreements, or warranties, if any, take place directly between the vendors and prospective users. |
| Apple, the Apple logo, Mac, PowerMac G4, PowerMac G5, Xserve, Xserve RAID, PowerBook, iBook, Airport, AirPort Extreme, iMac, eMac, iLife, iMovie, iCal, iPhoto, iTunes, QuickTime, FireWire, iPod, iSight, AppleWorks, Macintosh, Jaguar, Panther, Mac OS, Mac OS X and Mac OS X Server are trademarks of Apple Computer, Inc. |
|