Re: Sed and redirection into the same file
Brendon Oliver <[email protected]> Fri, 29 Sep 2006 16:13:09 +1000
| Newsgroups | gmane.org.user-groups.mlug.main |
|---|---|
| Message-ID | <[email protected]> |
On Friday 29 September 2006 15:53, Joshua Bassett wrote:
> It all appears to work fine, but the problem is when redirecting the
> output back into the same file...I end up with empty files! For
> example, the following works fine:
>
> for x in `grep -lr 'foo' app | grep -v "svn"`; do sed 's/foo/bar/'
> <${x} >${x}.new; done
>
> Clearly it's something to do with the <${x} >${x} part. What am I missing
> here?
You can't do in-place file edits with sed. Stick with what you found to work
and just rename the .new file if it's non-zero in size otherwise delete it.
e.g:
for x in `grep -lr 'foo' app | grep -v "svn"`
do
sed 's/foo/bar/'<${x} >${x}.new
if [ -s ${x}.new ]; then
mv ${x}.new ${x}
else
rm -f ${x}.new
fi
done
otherwise, use a perl one-liner (eg. perl -pie 's/foo/bar/'). Perl's -i
switch will do in-place file edits for you.
Cheers,
- brendon.
--
No man is useless who has a friend, and if we are loved we are indispensable.
-- Robert Louis Stevenson
16:12:22 up 3 days, 6:44, 1 user, load average: 0.31, 0.18, 0.12