简体   繁体   中英

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,

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

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

您可以使用cat和临时文件:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM