Replace a Whole File with Another File in Bash

Ive learned how to replace a line using bash script but I am wanting to learn how to replace a whole file with another file in a different folder with the same name. Is this possible??

4 Answers

cp -f [original file] [new file]

Copies the original file and overwrites the target file (hence -f which stands for "force").

6

In case you are attempting to copy just the content of the file try

cat /first/file/same_name > /second/file/same_name

This will overwrite all the content of the second file with the content from the first. However, your owner, group, and permissions of the second file will be unchanged.

1

Use these commands:

mv file1 file2

If file2 does not exist, then file1 is renamed file2. If file2 exists, its contents are replaced with the contents of file1.

mv -i file1 file2

Like above however, since the "-i" (interactive) option is specified, if file2 exists, the user is prompted before it is overwritten with the contents of file1.

mv file1 file2 file3 dir1

The files file1, file2, file3 are moved to directory dir1. dir1 must exist or mv will exit with an error.

mv dir1 dir2

If dir2 does not exist, then dir1 is renamed dir2. If dir2 exists, the directory dir1 is created within directory dir2.

3

Today I was in need of something same solution, only thing change is I need to replace old version of php file in many users directory with newer version. I'm heading here and just mix match with other stack's answer and solve my issue. I used @joseph code with find command.

I'm sharing my little code here, hope it will help someone.

for file in $(find /home/*/ -type f -name 'timthumb.php');
do
    cat /home/timthumb.php > $file;
done
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest