|
OSXFAQ Daily Unix Tricks

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