GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 8930

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??

Upvotes: 65

Views: 167738

Answers (4)

Nick Brunt
Nick Brunt

Reputation: 10067

cp -f [src file (will be copied)] [dst file (will be overwritten)]

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

Upvotes: 95

adaptable.services
adaptable.services

Reputation: 174

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

Upvotes: 5

Joseph
Joseph

Reputation: 938

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.

Upvotes: 57

user1635666
user1635666

Reputation: 123

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.

Upvotes: 10

Related Questions