The problem with the command
sed 'code' file > file
is that file
is truncated by the shell before sed actually gets to process it. As a result, you get an empty file.
The sed way to do this is to use -i
to edit in place, as other answers suggested. However, this is not always what you want. -i
will create a temporary file that will then be used to replace the original file. This is problematic if your original file was a link (the link will be replaced by a regular file). If you need to preserve links, you can use a temporary variable to store the output of sed before writing it back to the file, like this:
tmp=$(sed 'code' file); echo -n "$tmp" > file
Better yet, use printf
instead of echo
since echo
is likely to process \\
as \
in some shells (e.g. dash):
tmp=$(sed 'code' file); printf "%s" "$tmp" > file