On 20/12/2007, Bob Dunlop <bob.dunlop@???> wrote:
> On Thu, Dec 20 at 08:59, Keir Whitlock wrote:
> > Hi, A quick one for you, echo "hi" >> /tmp/file will append hi to the
> > end of file, but how do I prepend it to the top of the file?
>
> Since the filesystesm don't support a prepend function unlike append
> you'll have to resort to some application support.
>
> You could echo Hi to a new file, concatinate the old file onto it and
> move the result back. I prefer to edit in place as there is a better
> chance of preserving links/permissions etc, depending on your editor.
>
> I'd use.
>
> ed - /tmp/file <<EOF
> 1i
> hi
> .
> w
> q
> EOF
Using the sponge utility from moreutils, there's an alternative
method, which preserves file metadata:
( echo "This goes first"; cat /tmp/foo ) | sponge /tmp/foo
> But I'd probably think carefully about whether prepending to a file was
> actually the real requirement or whether I'd got something not quite
> right at a higher level.
I agree that there are often better ways to solve the problem.
G