TweetFollow Us on Twitter

Mac In The Shell: More from the Unknown

Volume Number: 23 (2007)
Issue Number: 07
Column Tag: Mac In The Shell

More from the Unknown

More shell tools that typically go unnoticed

by Edward Marczak

Introduction

OS X has an incredible breadth and depth available in the tools accessible from a shell. So much so, that it's hard to know each and every tool available. Some are almost hidden: tucked away in places one does not typically look. Others are hidden in plain sight: exactly where you'd expect them, but buried among the volume. This month, I'm going to dig out and introduce some more useful shell tools that you may not know about.

text manipulation

It's long been the domain of scripting languages like perl, and perhaps now to a lesser extent PHP, to slice, dice and otherwise manipulate text. However, there's a framework built right into OS X, so why not take advantage of it? The Cocoa text system is exposed to the shell via the "textutil" application. "textutil" can convert and manipulate many different formats of text documents. In fact, it works with a surprising number formats:

   txt
   html
   Microsoft Word "doc"
   Microsoft Word XML
   rtf
   webarchive

It's also incredibly easy to get started. Using the "-convert" switch, you can accomplish most conversions that you'd ever want:

textutil -convert html resume.doc

This will convert the Microsoft Word-based "resume.doc" into a separate HTML document named "resume.html". I'll immediately point out that textutil writes much, much better HTML than Word.

Note that the input format is determined 'automagically' by a number of methods. If textutil misidentifies the format of the source file, you tell it with the "-format" switch:

textutil -format html -convert rtf file1

This will tell textutil that "file1" is an HTML file, and we want to convert it into a rich text format file named "file1.rtf".

There's also a very handy "-info" switch that returns info on a given file:

$ textutil -info 2007-01-On\ Logs.doc
File:  2007-01-Marczak On Logs.doc
Type:  Word format
Size:  25600 bytes
Length:  3746 characters
Title:  MacTech Template
Author:  Classics Department
Last Editor:  Edward Marczak
Company:  Radiotope
Subject:  
Keywords:  
Created:  2006-11-02 17:56:00 -0500
Last Modified:  2006-11-06 09:47:00 -0500

As you can see, documents sometimes have incorrect metadata. Well, textutil can help you handle that as well! There are a number of metadata related switches:

strip: Remove metadata in target during conversion.

title: Set the title metadata attribute for output files.

author: Set the author metadata attribute for output files.

subject: Specify the subject metadata attribute for output files.

keywords: a shell-quoted list of 'tags' ("keyword1,keyword2, ...")

comment: Set the comment attribute for the output files.

editor: val Set the editor attribute for output files.

company: val Set the company attribute for output files.

creationtime: Set the creation time attribute for output files (in "yyyy-mm-ddThh:mm:ssZ" format).

modificationtime: Set the modification time attribute for output files (in "yyyy-mm-ddThh:mm:ssZ" format).

So, we could create an HTML document from a plain text file with the title and keywords set by running textutil like this:

textutil -convert html -title "Anti-gravity Thesis" -keywords "(anti,gravity,'atom power',physics)" -author "Bruce Banner" ag-file.txt

You'll find a well-formed HTML file with a little bit of CSS. Of course, there are many times when you need finer control over the tags that will be used in that HTML. Have no fear! The "-excludedelements" switch can help you out. This switch allows you to specify which HTML elements should not be used in the generated HTML. Like the "-keywords" switch, "-excludedelements" expects a single argument, so you can use a shell-quoted list of tags to skip.

Keep it clean

Speaking of well-formed HTML, manipulating tags and their parameters is a special case of text manipulation. Fortunately, tidy, the standard Unix utility just for this purpose, ships with OS X. So, if you've used textutil to generate HTML based output, tidy can take you even further.

The simplest case lets tidy modify your HTML document in place. To do so, use the "-m" switch:

$ tidy -im ag-file.html
Info: Doctype given is "-//W3C//DTD HTML 4.01//EN"
Info: Document content looks like HTML 4.01 Strict
No warnings or errors were found.

Take look at your file before and after running the tidy command. I also like to include the "-i" switch, which ensures tag levels are indented appropriately. Also, by default, tidy will lowercase all tags (which, by me, is "correct"). This can be overridden with the "-u" switch.

One of my absolute favorite uses of tidy is to get rid of "illegal" characters. This is easily accomplished with the "-b" (bare) switch. This strips the document of smart quotes, and dashes, and other characters that cause problems in HTML documents.

There's much, much more that tidy can do. Check the very well written man page to look at more options. Don't forget, though, that you can combine textutil and tidy into one neat shell statement:

textutil -stdout ag-file.txt -convert html | tidy -i -output ag-file.html

This command uses textutil to convert a text file to HTML, and sends the output to stdout. Then, that output is piped to tidy, which then requires us to use the "-output" switch to write the file to disk.

Finally, realize that both textutil and tidy can be used with a wildcard character to process an entire group of files. If all files are in a single directory, simply change to that directory and:

textutil -convert html *.doc

This will convert all Word documents in the current directory into HTML files. To process the current folder and all subfolders, use the find utility:

find . -name \*txt -print0 | xargs -0 textutil -convert html

I opted for xargs over find's exec command to ensure that large directories can be processed. You can scrub Word metadata in-place using this technique:

textutil -strip -convert doc *.doc

Painless, right?

Image Manipulation

While slinging text around may be a common, and very specific operation, doing the same to images requires a different set of tools. OS X's scriptable image processor server or, "sips" is just the ticket.

Like textutil, sips leans on frameworks already built into the core of OS X. This, of course, lets you do all of the great things that you can with a GUI right in a shell! Why is this exciting? Automation, naturally.

In the past, I've put together both nightly reports and 'one-click-builds' of documents using both user submitted and random images. The trick is not so much the content, but the dimensions of the graphic: you need consistent dimensions so you can automate your layout. Resizing graphic files is one of the things that sips does best:

sips -Z 100x100 IMG_1312.JPG --out image1-sized.jpg

The "-Z" switch is really nice: it keeps the proportions of the original image, but makes sure neither the width or height exceed the dimensions specified. The "--out" switch writes the result to a new file. The image you just made doesn't have a nice preview icon in the Finder? Add one:

sips -i image1-sized.jpg

Oh, you didn't want a JPEG format file? Convert it at the same time using the "-s" (setProperty) switch (let's do it all in one shot):

sips -Z 100x100 IMG_1312.JPG -i -s format png --out image-sized.png

This one command resizes the graphic, converts the output to png and creates the Finder preview icon. Nice.

For automation, though, you often need to find out information about the source before you blindly process it. Again, like textutil, sips has functions for this. You can dump all of an image's data with the "-g all" switch and parse the output yourself:

$ sips -g all IMG_1312.JPG 
/Users/erm/Pictures/Parade/IMG_1312.JPG
  pixelWidth: 2592
  pixelHeight: 1944
  typeIdentifier: public.jpeg
  format: jpeg
  formatOptions: default
  dpiWidth: 180.000
  dpiHeight: 180.000
  samplesPerPixel: 3
  bitsPerSample: 8
  hasAlpha: no
  space: RGB
  profile: Camera RGB Profile
  creation: 2007:04:04 17:23:31
  make: Canon
  model: Canon PowerShot S2 IS

...or, you can request one or more of these parameters directly:

$ sips -g pixelWidth -g pixelHeight IMG_1312.JPG
/Users/marczak/Pictures/Parade/IMG_1312.JPG
  pixelWidth: 2592
  pixelHeight: 1944

Like textutil, feel free to throw a wildcard at sips, or, use the find/xargs trick.

Why?

So, why go through this trouble, when you can fire up Photoshop and make your changes (and even script it!), or use a Word processor to mold your words? Again, automation comes to mind. Specifically, automation with low overhead. Using the shell tools, you can run scripts on a server without having a GUI or installing an application like Photoshop at all. Combine this with some of the techniques I presented in April, and you can achieve some incredibly complex workflows.

Even cooler: more and more GUI utilities have some way to run shell jobs. Textmate, for example, can run a selection or entire document through a shell tool and plop the results right back in the live document. Even apps that don't have this functionality built in can usually be faked thanks to AppleScript. Take Mail.app, for instance. It lets you create signatures, but not dynamic signatures that rely on a running process. What if you wanted to include a snapshot from your iSight in your sig? Script a capture from isightcapture (http://www.intergalactic.de/hacks.html), run it through sips and AppleScript the copy and pasting of into Mail.

Or, consider a simpler alternative: you've installed fortune and want a random fortune in your sig. A simple bash script could be as follows:

#!/bin/bash
# Tell Mail.app to select all and copy to clipboard
osascript <<MailCopy
tell application "System Events"
        tell application "Mail" to activate
        keystroke "a" using {command down}
        keystroke "c" using {command down}
end tell
MailCopy
# Write clipboard to file
pbpaste > /tmp/mailpaste.tmp
fortune -s >> /tmp/mailpaste.tmp
textutil -stdout -convert rtf /tmp/mailpaste.tmp | pbcopy
# Tell Mail.app to activate and paste in the contents of the clipboard
osascript <<MailPaste
tell application "System Events"
        tell application "Mail" to activate
        keystroke "a" using {command down}
        keystroke "v" using {command down}
end tell
MailPaste

This is admittedly a quick hack with absolutely no error checking or other niceties. However, if you open up Mail.app, create a new message, put your cursor anywhere in the body and run this, you'll get a fortune tagged onto the end of your message (it helps if you already have a sig created). Pretty it up a bit and you could run it via the GUI via a ".command" file, or, wrap it in AppleScript and run it from your script menulet. Or, if you're a Quicksilver user, don't ignore the qs shell tool.

Of course, the real power lies in integrating other data: from the web, from Excel, from a database....wherever!

Conclusion

When venerable shell tools are integrated with the power of OS X, the workflow possibilities truly are endless. Be creative in your application of scripting tools, and you'll be able to solve any problem for your client/employer/self.

Media of the month: Brendan Benson's new album, "Alternative to Love". It's just good, fun pop music, no strings attached.

Until next month, keep thinking of ways to keep the work flowing.

References:

"Developer Release Note": http://developer.apple.com/releasenotes/Cocoa/AppKit.html


Ed Marczak owns and operates Radiotope, a technology consultancy that just tries to make life easier through the technology that already exists. He's also the Executive Editor of MacTech Magazine, and CTO of WheresSpot. His copious free time is spent with his wife and two daughters, currently enjoying the weather in the North East U.S.

 
AAPL
$441.35
Apple Inc.
+1.69
MSFT
$34.61
Microsoft Corpora
-0.24
GOOG
$889.42
Google Inc.
-17.55

MacTech Search:
Community Search:

Software Updates via MacUpdate

SteerMouse 4.1.6 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
Google Chrome 27.0.1453.93 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Labels & Addresses 1.6.5 - Powerful...
Labels & Addresses is a home and office tool for printing all sorts of labels, envelopes, inventory labels, and price tags. Merge-printing capability makes the program a great tool for holiday... Read more
KeyCue 6.5 - Displays all menu shortcut...
KeyCue helps you to use your OS X applications more effectively. Just hold down the Command key for a while - KeyCue comes to help and shows a table of all currently available keyboard shortcuts.... Read more
HoudahSpot 3.7.8 - Advanced front-end fo...
HoudahSpot is a flexible file-search tool based on Apple's powerful Spotlight engine. Keep frequently used files within reach Retrieve the files you didn't know you still had Don't waste time... Read more
Cobook Contacts 1.2.6 - Intelligent addr...
Cobook Contacts is a better address book that makes contact management enjoyable for millions of people every day. Find contacts faster and organize them with tags. Get integrated social profiles... Read more
AppDelete 4.0.7 - Delete your unwanted a...
AppDelete is an uninstaller for Macs that will remove not only applications but also widgets, preference panes, plugins and screensavers along with their associated files. Without AppDelete these... Read more
OnyX 2.6.9 - Maintenance and optimizatio...
OnyX is a multifunctional utility for OS X. It allows you to verify the startup disk and the structure of its System files, to run miscellaneous tasks of system maintenance, to configure the hidden... Read more
Apple iTunes 11.0.3 - Manage your music,...
Apple iTunes lets you organize and play digital music and video on your computer. It can automatically download new music, app, and book purchases across all your devices and computers. And it's a... Read more
Spotify 0.9.0.133. - Stream music, creat...
Spotify is a new way to enjoy music. Simply download and install. Before you know it you'll be singing along to the genre, artist, or song of your choice. With Spotify you are never far away from... Read more

Logitech To Release Wired Keyboard With...
Logitech To Release Wired Keyboard With The Classroom In Mind Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] Logitech has created a wired keyboard for the iPad which | Read more »
Pocket Informant Pro Completely Redesign...
Pocket Informant Pro Completely Redesigns Interface In Latest Update Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] | Read more »
Warhammer 40,000: Armageddon Brings The...
Warhammer 40,000: Armageddon Brings The Second War of Armageddon To iOS, Next Year Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] Strategy game creator, Slitherine, unleashes Armageddon, its firs | Read more »
World of Aircraft MMO Flies Into Action
World of Aircraft MMO Flies Into Action Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
iBillionaire Compares Your Stock Market...
iBillionaire Compares Your Stock Market Portfolio To Actual Billionaire Portfolios Posted by Andrew Stevens on May 22nd, 2013 [ | Read more »
Greedy Grub Gets A Nature Filled Gamepla...
Greedy Grub Gets A Nature Filled Gameplay Trailer, Launches This Week Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] Greedy Grub, a fun simulation game based on the work of comic artis | Read more »
OmniPresence Automatic Document Syncing...
OmniPresence Automatic Document Syncing Is Now Available Posted by Andrew Stevens on May 22nd, 2013 [ permalink ] The Omni Group has released OmniPresence, bringing automatic document syncing to OmniGraffle, OmniOutliner, a | Read more »
Zoombies: Animales de la Muerte! Review
Zoombies: Animales de la Muerte! Review By Carter Dotson on May 22nd, 2013 Our Rating: :: FIESTA!iPad Only App - Designed for the iPad Yes, a game about taking on hordes of zombified animals is as good as it sounds.   | Read more »
THX tune-up™ Review
THX tune-up™ Review By Michael Carattini on May 22nd, 2013 Our Rating: :: EASY TV DISPLAY ADJUSTMENTUniversal App - Designed for iPhone and iPad THX tune-up is a fantastic utility that makes it simple and easy to adjust your TV’s... | Read more »
Earth Invasion Episode I: Eclipse Review
Earth Invasion Episode I: Eclipse Review By Campbell Bird on May 22nd, 2013 Our Rating: :: FIGHT OFF THE "BUGS"Universal App - Designed for iPhone and iPad Earth Invasion Episode I: Eclipse is a real-time strategy game that is... | Read more »

Price Scanner via MacPrices.net

Platform Wars: Tablets Triumphant, But Don’t Write...
The Register’s Paul Kunert says it’s finally official – the epic battle of legendary Apple CEO Steve Jobs is finally won, now that he has toppled the PC platform from beyond the grave, in the UK, at... Read more
Apple Tops 100 Most Valuable Global Brands 2013 Su...
MarketingWeek’s Lou Cooper reports that this years BrandZ ranking of the top 100 valuable global brands sees Apple maintain its reign as number one, ahead of Google and IBM in second and third and... Read more
How To Create A 4GB/S RAM Disk In Mac OS X
TekRevue notes that RAM Disks, as the name indicates, are logical storage volumes created using a computers memory (RAM) instead of a traditional hard drive or solid state drive. Back in the day, RAM... Read more
How To Factory Reset On An iPhone or iPad
PC Advisor’s Jim Martin notes that when you come to sell your iPhone or iPad – or even give it to a family member – you should erase all the data and restore it to factory settings to avoid handing... Read more
HGST Launches 1.5TB Capacity in Standard 2.5-inch...
HGST (formerly Hitachi Global Storage Technologies and now a Western Digital company) continues to push technology innovation by offering the highest storage density (MB/mm3) of any hard disk drive (... Read more
iPads with Retina Displays (Apple refurbished) ava...
The Apple Store has Apple Certified Refurbished 4th generation iPads with Retina Displays, Wi-Fi & Cellular, available for $50 off MSRP. Apple’s one-year warranty is included with each iPad, and... Read more
Apple MacBook Orders To Rise 20% Sequentially In 2...
Digitimes’ Aaron Lee and Joseph Tsai say that with Apple ready to release its new MacBook products in the near future, sources from the upstream supply chain have revealed that orders for MacBook... Read more
Trial Production of 5th-Generation iPad To Begin R...
Digitimes’ Max Wang and Adam Hwang report that trial production of Apple’s 5th-generation 9.7-inch iPad will begin soon with volume production to begin in July, and monthly shipments ramping up to 2-... Read more
Dell’s $100 Thumb-Sized Android PC To Ship In July...
9to5google.com says that Dell’s Project Orphelia, a thumb-sized drive that turns any display with an HDMI port into an Android PC, is to start shipping in July at a price of around $100 according to... Read more
MacBook Airs (Apple refurbished) available startin...
 The Apple Store has Apple Certified Refurbished 2012 MacBook AIrs available for up to $240 off MSRP, with models starting at $849. An Apple one-year warranty is included with each model, and... Read more

Jobs Board

Mac/ *Apple* Specialist Needed | Enterp...
Mac/ Apple Specialist Needed | Enterprise iPad Deployment A prominent Robert Half client is seeking out a Mac/ Apple Specialist to assist with an iPad deployment Read more
Class 1 District *Apple* Technician -...
QUALIFICATIONS: High School diploma Associate Degree in Technology preferred. Apple Certified Support Professional Mac OS X 10.5, 10.6, 10.7, 10.8 Apple Certified Read more
*Apple* At-Home Team Manager - Apple (U...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
Class 1 District *Apple* Technician -...
QUALIFICATIONS: High School diploma Associate Degree in Technology preferred. Apple Certified Support Professional Mac OS X 10.5, 10.6, 10.7, 10.8 Apple Certified Read more
*Apple* Infrastructure Engineer II - Ba...
39964 Apple Infrastructure Engineer II Full Time Regular posted 04/22/2013 San Ramon, CA San Francisco, CA Requirements What sets Bank of the West apart from other banks Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.