ltsBlog

Why `sed -i’ exists

I’ve decided to to a morning-pages type thing here, just to get info out. This means that I’ll be posting 250-ish word weblog post
snippits sharing whatever, and fairly frequently posting, if this works.

So, what is the purpose of the -i flag to sed? Simply, it edits the file in place, instead of dumping the edit to stdout.

Those of you familiar with “cat -v Considered Harmful” or just traditional UNIX design will say “bah, what a useless flag, just use sed 's/regex//' < file > file to write the changes back to the file.

But there’s a problem with this. There is a race condition, the file has been opened twice, once for reading, and once for writing. If they get closed in the wrong order, you will end up with an empty file. In my experience this very seldom happens. However, when you have a shell script that usually works, but just occaisionally corrupts your `database’, you’ll see why sed -i‘s important.

This entry was posted in Computers, morning-pages. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>