Hao Shen
Hao Shen

Reputation: 2735

In bash script, is it possible to echo something into the beginning of file?

I know by

echo text >> file.txt

I can append the "text" to the end of the file file.txt

But is it possible to insert something at the beginning of the file without removing the existing content?

Thanks,

Upvotes: 2

Views: 2872

Answers (3)

gniourf_gniourf
gniourf_gniourf

Reputation: 46833

You can use ed, the standard editor:

stuff="this is the stuff you want to prepend to file"
ed -s file.txt < <(printf '%s\n' 1 i "$stuff" . wq) > /dev/null

If you have several lines to add, put them in an array, like so:

stuffs=( "this is the first line you want to prepend to file" "lalala the second line" "my gorilla loves bananas in this third line" )
ed -s file.txt < <(printf '%s\n' 1 i "${stuffs[@]}" . wq) > /dev/null

The only limitation is inserting a line that only consists of a single period. Sigh.

ed is the standard editor. This method involves no temp files! if you choose this method, you'll genuinely be editing the file (so you won't change permissions and ownerships). It's probably one of the most efficient methods. A more efficient method (used for huuuuge files) is to deal directly with dd. But you certainly don't want that here.

As Georgi Kirilov suggests in the comments below, you can use this method without any bashisms as so:

stuffs=( "I love oranges, but my gorilla loves bananas" )
printf '%s\n' 1 i "$stuff" . wq | ed -s file.txt > /dev/null

provided your system comes with a printf (and very, very likely it does).

Upvotes: 4

Murph
Murph

Reputation: 1509

You can use cat and a temporary file:

echo 'text' | cat - file.txt > temp && mv temp file.txt

Upvotes: 4

anubhava
anubhava

Reputation: 785246

Yes you can do it via sed:

sed -i '' '1i\
some-text
' file

OR using awk:

awk -v T=some-text 'NR==1{print T} 1' file

Without any external utility:

echo -e "some-text\n$(<file)" > file

Upvotes: 3

Related Questions