views:

42

answers:

1

I have the following sed -e 's/<em\:update.*//g' install.rdf > install.rdf in a bash script, and it works on command line, but in the bash script install.rdf ends up a blank file.

When I run sed -e 's/<em\:update.*//g' install.rdf > install.rdf command line, then 2 lines are stripped out of the file.

Any idea why sed -e 's/<em\:update.*//g' install.rdf > install.rdf is not working in the bash script?

+4  A: 

Try this:

sed -i -e 's/<em\:update.*//g' install.rdf

When you redirect output to a file in truncate mode, the file is truncated first, before it's read. Thus, the result is an empty file. Using sed -i avoids this.

Portable (and hopefully not too insecure) solution:

(set -C &&
 sed -e 's/<em\:update.*//g' install.rdf > install.rdf.$$ &&
 mv install.rdf.$$ install.rdf)

:-)

Chris Jester-Young
However, `-i` is a GNU extension.
Matthew Flaschen
@Matthew: Thanks! Fixed up the answer with something a little more general (albeit insecure if the directory is writable by malicious parties).
Chris Jester-Young
The shell variable $$ is classically used for non-hostile environments avoiding problems with shared names: `sed ... install.rdf > install.rdf.$$; mv install.rdf.$$ install.rdf`.
Jonathan Leffler
@Jonathan: I've revised my solution with your suggestion, as well using `set -C` to mitigate symlink attacks or anything. It can fail if the filename is already taken, but at least people can't trick you into clobbering files you don't intend to. ;-)
Chris Jester-Young