1

In bash script, if I do this:

cat infile >> outfile

the content of "infile" is added from the last line of "outfile".

infile:

foo
bar

outfile:

superfoo
superbar

after cat command:

superfoo
superbar
foo
bar

but I want:

foo
bar
superfoo
superbar

How can I change this?

acgbox
  • 312
  • 2
  • 13

2 Answers2

3

You need to use a temporary file:

cat infile outfile > outfile.tmp && mv outfile.tmp outfile
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You can use the following command:

echo "$(cat infile outfile)" > outfile

In this case you don't need a temporary file.

milanbalazs
  • 4,811
  • 4
  • 23
  • 45
  • Reading an arbitrary amount of content into RAM is probably something that should be made explicit. If we're dealing with large enough files, this can be a much worse solution than the temporary file approach. (And why the two separate `cat`s, instead of just `"$(cat infile outfile)"`? Either way, you're relying on the command substitution to be performed before the outer redirection does an `open("outfile", O_TRUNC|O_WRONLY)`.) – Charles Duffy Nov 07 '19 at 20:58
  • Yes, you are right, perhaps this is not the best solution in case of quite large files but the questioner didn't mentioned so large files. And also your are right, we can combine the two `cat` commands. I am editing my answer. Thanks for your remark! – milanbalazs Nov 07 '19 at 21:02
  • I'd also suggest `printf '%s\n' "$(cat ...)"` instead of using `echo` -- see the caveats in the APPLICATION USAGE section of the [POSIX `echo` spec](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html). – Charles Duffy Nov 07 '19 at 21:04
  • I did not specify the size of the file, but I require a solution that applies to any scenario, so I did not select your answer. However, I thank you very much for your command. – acgbox Nov 07 '19 at 21:18