Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83408

echo >> style appending, but to the beginning of a file

Is there any nice trick in UNIX shell to append lines to the beginning of a file? E.g. akin to

   echo "Foobar" >> file.txt

... but instead new lines would prepend the existing ones?

Upvotes: 8

Views: 10988

Answers (3)

Sofia Pahaoja
Sofia Pahaoja

Reputation: 2720

I'd keep it simple. The easiest and probably fastest solution is straightforward:

(echo "Foobar"; cat file.txt) >tmpfile
cp tmpfile file.txt
rm tmpfile

If it doesn't matter that file.txt's inode changes, replace the "cp" by "mv". A solution significantly faster than this is not possible, because Unix filesystem semantics don't support prepending to a file, only appending.

Upvotes: 3

William Pursell
William Pursell

Reputation: 212258

This is nonstandard, but if your sed supports -i you can do:

sed -i '1i\
Foobar' file.txt

Upvotes: 6

ott--
ott--

Reputation: 5722

In 2 steps:

content=$(cat file.txt) # no cat abuse this time
echo -en "foobar\n$content" >file.txt

Upvotes: 10

Related Questions