到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:

文件内容

some text at the beginning

结果

<added text> some text at the beginning

它很相似,但是我不想用它创建任何新的行…

如果可能的话,我希望用sed来做这件事。


当前回答

使用shell:

echo "$(echo -n 'hello'; cat filename)" > filename

不幸的是,命令替换将删除文件末尾的换行符。为了保持它们,人们可以使用:

echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename

既不需要分组,也不需要命令替换。

其他回答

插入换行符:

sed '1i\\'

如果文件只有一行,你可以使用:

sed 's/^/insert this /' oldfile > newfile

如果它不止一行。之一:

sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile

我已经包括了后者,以便您知道如何进行行范围。这两种方法都用要插入的文本“替换”受影响行的开始行标记。您还可以(假设您的sed足够现代)使用:

sed -i 'whatever command you choose' filename

进行就地编辑。

在文件顶部添加一行:

sed -i '1iText to add\'

别名是另一种解决方案。添加到你的init rc/ env文件:

addtail () { find . -type f ! -path "./.git/*" -exec sh -c "echo $@ >> {}" \; }
addhead () { find . -type f ! -path "./.git/*" -exec sh -c  "sed -i '1s/^/$@\n/' {}" \; }

用法:

addtail "string to add at the beginning of file"
addtail "string to add at the end of file"

Sed可以对地址进行操作:

$ sed -i '1s/^/<added text> /' file

每个答案上神奇的1是什么?行解决!

想在前10行添加<添加的文本> ?

$ sed -i '1,10s/^/<added text> /' file

或者你可以使用命令分组:

$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}