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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.