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 - More printf

By Adrian Mayo - Editor - OSXFAQ

We can take advantage of a very useful feature of printf to print tables of data. Check this example:

$ printf "<tr>\n  <td>%s</td>  <td>%s>/td>\n</tr>\n" Apples 7 Pineapples 5 Pears 6
<tr>
  <td>Apples</td>  <td>7</td>
</tr>
<tr>
  <td>Pineapples</td>  <td>5</td>
</tr>
<tr>
  <td>Pears</td>  <td>6</td>
</tr>
$ 

The printf statement prints what's in its format string. %s tells printf to look outside the format string for a value to substitute. Because the format string has two occurrences of %s, but we supply six values, it takes three sweeps at the string.

Using the next trick, we can read the values from a file.

$ echo "Apples 7 Pineapples 5 Pears 6" > fruit-count
$ printf "<tr>  <td> %s</td>  <td>%s</td>\n</tr>\n" $(cat fruit-count)
<tr>
  <td>Apples</td>  <td>7</td>
...

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.