I've been trying to append file.bak into file.php using this command:

sed r file.php file.bak

It gives correct output as desired. However, it doesn't save that appended file.bak into file.php.

Any idea how to get it done?


You don't need sed for this. It's enough to use cat:

cat file.bak >>file.php

This will append the contents of file.bak to the very end of file.php.

The sed program r file.php will output the contents of file.php to standard output for each line of input. If file.bak has multiple lines, you will get multiple copies of file.php inserted.

This is not what you want if you want to use sed to append the data.

Instead, ignoring the fact that cat does a better job here,

sed '$r file.bak' file.php

This will not read file.bak until reaching the very last line of file.php. This has the effect of concatenating the contents of the two files (the contents of file.php will come first, followed by the contents of file.bak).

To write the result back to file.php you may either redirect the output to a new file and then move that into place (the safe way):

sed '$r file.bak' file.php >tmpfile && mv tmpfile file.php

or, you may use the -i option that some implementations of sed has (the unsafe way):

sed -i '$r file.bak' file.php
| improve this answer | |
  • I used cat option but it's appending at the top of file, how can it be appended at the bottom? – CryptoMiningPoolSetupYiimp Apr 26 '18 at 9:00
  • @CryptoMiningPoolSetupYiimp I might well have misunderstood what file you wanted to add to the end. cat file1 >>file2 will add the contents of file1 to the end of file2. Modify this command to fit your particular situation. – Kusalananda Apr 26 '18 at 9:02
  • @CryptoMiningPoolSetupYiimp I interpreted "append file.bak into file.php" as "append file.bak to the end of file.php"... – Kusalananda Apr 26 '18 at 9:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.