如何使用cat将文本文件的内容添加到文件的开头

how to add content of text file to the beginning of file with cat

在 bash 脚本中,如果我这样做:

cat infile >> outfile

"infile"的内容是从"outfile"的最后一行添加的。

infile:

foo
bar

输出文件:

superfoo
superbar

在 cat 命令之后:

superfoo
superbar
foo
bar

但我想要:

foo
bar
superfoo
superbar

我该如何更改?

您需要使用临时文件:

cat infile outfile > outfile.tmp && mv outfile.tmp outfile

您可以使用以下命令:

echo "$(cat infile outfile)" > outfile

在这种情况下,您不需要临时文件。