How to insert a text at the beginning of a file?

2019-01-04 06:30发布

So far I've been able to find how to add a line at the beginning of a file but that's not exactly what I want. I'll show it on a example

File content

some text at the beginning

Result

<added text> some text at the beginning

It's similar but I don't want to create any new line with it...

I would like to do this with sed if possible.

标签: linux bash sed
13条回答
闹够了就滚
2楼-- · 2019-01-04 06:47

There is a very easy way:

echo "your header" > headerFile.txt
cat yourFile >> headerFile.txt
查看更多
三岁会撩人
3楼-- · 2019-01-04 06:48
echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt

The first tac pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac wraps it once again so the inserted line is at the beginning and the original file is in its original order.

查看更多
Luminary・发光体
4楼-- · 2019-01-04 06:50

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

The best solution will add the string, but with the string, it will not add a line at the end of a file.

sed -i '1s/^/your text\n/' file
查看更多
再贱就再见
5楼-- · 2019-01-04 06:50

my two cents:

sed  -i '1i /path/of/file.sh' filename

This will work even is the string containing forward slash "/"

查看更多
干净又极端
6楼-- · 2019-01-04 06:57

Note that on OS X, sed -i <pattern> file, fails. However, if you provide a backup extension, sed -i old <pattern> file, then file is modified in place while file.old is created. You can then delete file.old in your script.

查看更多
\"骚年 ilove
7楼-- · 2019-01-04 06:57

To add a line to the top of the file:

sed -i '1iText to add\'
查看更多
登录 后发表回答