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
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 Daily Unix Tricks   back to index

Week 73 - Useful Scripts (15 March 2004)

by Adrian Mayo - Senior Editor for Mac OS X Unix

Friday - Sed Extension

Create a simple wrapper for the 'sed' command (or any similar command) to enable it to process a file directly. Normally sed uses standard in and out, and cannot write back to its input file.

$ cat sedx
#!/bin/sh
tmp=tmp-file-for-$PPID
{    sed "$1" "$2" > $tmp \
  && mv $tmp "$2"
} || rm $tmp  

Note that the more obvious line:

sed "$1" "$2" > $tmp ; mv $tmp "$2"

should not be used as an error in the sed script will cause all files to be wiped.

Use sedx in this way:

$ sedx 's/XXX/ZZZ/' index.html

to apply the sed command to index.html.

The script as given takes only one input file. Use the scripts from Wednesday and Thursday to process multiple files.

Apply to all files in the current directory:

$ each \*.html sedx 's/XXX/YYY/'

Or to all files in the directory hierarchy (recursively):

$ reach \*.html sedx 's/XXX/YYY/'

Add parameter checking to the script:

$ cat sedx
#!/bin/sh

if [ "$2" = "" -o "$1" = "-usage" ]; then echo "Executes a sed command writing back to the original file." echo "Usage: ${0##*/} sed-command file" echo "Or use with (r)each" echo "Usage: (r)each filetype ${0##*/} sed-command" exit fi
tmp=tmp-file-for-$PPID { sed "$1" "$2" > $tmp \ && mv $tmp "$2" } || rm $tmp

Discuss this trick in the Learning Center forum


If you want to learn more about Mac OS X Unix visit the Learning Center  click.

  • For beginners: the Mac OS X Unix Tutorial
  • For detailed information on specific topics: Mac OS X Advanced Unix
  • For answers to common problems: Mac OS X How To

Copyright © 2000-2010 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.