DirectNET

Data Center Management Solutions including UPS Systems, Data Center Cooling, KVM over IP & IP Power Strips, Server Racks and Server Rack accessories; KVM Switches and KVM Extenders; Rackmount Monitors and Rackmount Keyboards.


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

OUR PARTNERS

OSXFAQ Mac OS X UNIX Tip-of-the-Day  back to index

Scripting One-Liners - Fancy Printing

By Adrian Mayo - Editor - OSXFAQ

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

Visit the Site of the Book of the Unix Tips:
Projects 56 and 63 cover printf in more depth.


Discuss this trick in the OSXFAQ Learning Center forum

E-mail your comments or suggestions to webmaster@osxfaq.com


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.