公告
财富商城
积分规则
提问
发文
2019-01-12 23:44发布
【Aperson】
Is there a Unix command to prepend some string data to a text file?
Something like:
prepend "to be prepended" text.txt
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.
tee
> /dev/null
printf '%s\n%s\n' "to be prepended" "$(cat text.txt)" >text.txt
I didn't really like any of the answers here, so I built my own command: pre.
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.
sponge
moreutils
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
最多设置5个标签!
In some circumstances prepended text may available only from stdin. Then this combination shall work.
If you want to omit
tee
output, then append> /dev/null
.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
frommoreutils
on the end to save the file.This is one possibility:
you'll probably not easily get around an intermediate file.
Alternatives (can be cumbersome with shell escaping):