Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 571
Hao Shen Avatar asked Nov 21 '25 16:11

Hao Shen


2 Answers

You can use cat and a temporary file:

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

like image 81
Murph Avatar answered Nov 23 '25 08:11

Murph


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).

like image 20
gniourf_gniourf Avatar answered Nov 23 '25 08:11

gniourf_gniourf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!