简体   繁体   English

在bash脚本中,是否可以将某些内容回显到文件的开头?

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

I know by 我知道

echo text >> file.txt echo text >> file.txt

I can append the "text" to the end of the file file.txt 我可以将“text”附加到文件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做到:

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

OR using awk: 或使用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: 您可以使用ed ,标准编辑器:

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. ed是标准编辑器。 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 . 更有效的方法(用于huuuuge文件)是直接处理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: 正如Georgi Kirilov在下面的评论中建议的那样,你可以使用这种方法而不需要任何基本原理:

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). 如果你的系统附带了printf (非常非常可能)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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