General UNIX puzzle

Bill Campbell freebsd at celestial.com
Sat Jan 17 14:04:02 PST 2004


On Sat, Jan 17, 2004, Brett Glass wrote:
>At 02:44 PM 1/17/2004, Eric Anderson wrote:
>
>>You should do your own Comp Sci homework. This looks like (especially considering the time of th year) the begining of a Unix Basics course.
>
>Nope; I'm quite experienced with UNIX. However, I posted the
>question because I wanted to see what the most efficient
>and clever answers would be. For example, while I received
>answers involving languages, such as sed and awk, the simplest 
>answer to at least one of them seems to use grep.

All of those (sed, awk, grep) involve making a copy of the original file
which can cause problems with ownership, permissions, concurrent access,
etc.  The gnu shtool is one of the most useful tools for this for in-place
updates that's considerably more friendly than the ``ed'' examples I posted
(truncated by my mailer for some reason).  One can use multiple sed
commands in one step:

shtool subst [-s] \
	-e '99d' \
	-e '/pattern1/s/$/\ninsert line after line with pattern1/' \
	-e '/pattern2/s/^/\ninsert line before pattern 2/' \
	-e '/pattern3/s/pat1/pat2/g' \
	file1 [file2, ....]

The -s option preserves the timestamps of the file(s) edited.

Remember if doing things based on line numbers (a) to make these changes
first from highest line number to lowest to prevent confusion.

The two lines with pattern1 and pattern2 require sed that recognizes the \n
escape sequence (gnu-sed does, FreeBSD doesn't).

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

A Galileo could no more be elected president of the United States than
he could be elected Pope of Rome.  Both high posts are reserved for men
favored by God with an extraordinary genius for swathing the bitter
facts of life in bandages of self-illusion.
                -- H. L. Mencken


More information about the freebsd-questions mailing list