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 07:10

If the file is only one line, you can use:

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

If it's more than one line. one of:

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

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

sed -i 'whatever command you choose' filename

to do in-place editing.

查看更多
登录 后发表回答