Unix command to prepend text to a file

2019-01-12 23:44发布

Is there a Unix command to prepend some string data to a text file?

Something like:

prepend "to be prepended" text.txt

16条回答
可以哭但决不认输i
2楼-- · 2019-01-13 00:31

In some circumstances prepended text may available only from stdin. Then this combination shall work.

echo "to be prepended" | cat - text.txt | tee text.txt

If you want to omit tee output, then append > /dev/null.

查看更多
Viruses.
3楼-- · 2019-01-13 00:33
printf '%s\n%s\n' "to be prepended" "$(cat text.txt)" >text.txt
查看更多
爷、活的狠高调
4楼-- · 2019-01-13 00:33

I didn't really like any of the answers here, so I built my own command: pre.

Install with go:

go get -u github.com/Flaque/pre

Prepend some text from stdin to a file with:

echo "some at the start" | pre myFile.txt | sponge myFile.txt

The command doesn't write in place, it just outputs to stdout, so you'll need the sponge from moreutils on the end to save the file.

查看更多
别忘想泡老子
5楼-- · 2019-01-13 00:36

This is one possibility:

(echo "to be prepended"; cat text.txt) > newfile.txt

you'll probably not easily get around an intermediate file.

Alternatives (can be cumbersome with shell escaping):

sed -i '0,/^/s//to be prepended/' text.txt
查看更多
登录 后发表回答