[英]In bash script, is it possible to echo something into the beginning of file?
我知道
echo text >> file.txt
我可以将“text”附加到文件file.txt的末尾
但是有可能在文件的开头插入一些内容而不删除现有内容吗?
谢谢,
是的,你可以通过sed做到:
sed -i '' '1i\
some-text
' file
或使用awk:
awk -v T=some-text 'NR==1{print T} 1' file
没有任何外部工具:
echo -e "some-text\n$(<file)" > file
您可以使用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
如果要添加几行,请将它们放在一个数组中,如下所示:
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
唯一的限制是插入一个只包含一个句点的行。 叹。
ed
是标准编辑器。 此方法不涉及临时文件! 如果您选择此方法,您将真正编辑该文件(因此您不会更改权限和所有权)。 它可能是最有效的方法之一。 更有效的方法(用于huuuuge文件)是直接处理dd
。 但你肯定不希望这里。
正如Georgi Kirilov在下面的评论中建议的那样,你可以使用这种方法而不需要任何基本原理:
stuffs=( "I love oranges, but my gorilla loves bananas" )
printf '%s\n' 1 i "$stuff" . wq | ed -s file.txt > /dev/null
如果你的系统附带了printf
(非常非常可能)。
您可以使用cat和临时文件:
echo 'text' | cat - file.txt > temp && mv temp file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.