Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have several files of the same name (say, somefile.php) scattered within several directories under /var/

If I want to replace all of them with a new version of somefile.php located in, say, /home/me/somefile.php ... how would I do that? Every search result I find relates to replacing text in a file but I want to replace the entire file.

I know I can find all the files with:

find /var/ -type f -name somefile.php 

But I'm not sure how to move /home/me/somefile.php into the results and replace 'em all.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

find /var -type -f -name somefile.php -exec cp /home/me/somefile.php {} \;

be careful!

share|improve this answer
    
this 'replaces the content' only, as the OP said. I guess he wants to rename the found file to the same name the new file has AND replace its contents ... –  m.sr Aug 25 '10 at 21:51
    
The correct syntax is find /var -type f (not -f). What do do you mean by whole content? –  ring0 Aug 26 '10 at 2:13

As you see, this works with files with whitespaces too:

hoeha@dw:/tmp/test$ mkdir my\ dir{1,2,3}/ ; touch my\ dir{1,2,3}/file\ to\ replace
hoeha@dw:/tmp/test$ tree
.
├── my dir1
│   └── file to replace
├── my dir2
│   └── file to replace
└── my dir3
    └── file to replace

3 directories, 3 files
hoeha@dw:/tmp/test$ echo "the new one" > the\ new\ one
hoeha@dw:/tmp/test$ find . -type f -name 'file to replace' -exec cp the\ new\ one \{\} \; -execdir mv \{\} the\ new\ one \;
hoeha@dw:/tmp/test$ tree
.
├── my dir1
│   └── the new one
├── my dir2
│   └── the new one
├── my dir3
│   └── the new one
└── the new one

3 directories, 4 files
hoeha@dw:/tmp/test$ cat my\ dir1/the\ new\ one
the new one
hoeha@dw:/tmp/test$ find -version | head -1
find (GNU findutils) 4.4.2
hoeha@dw:/tmp/test$ 

Is this what you wanted?

share|improve this answer

GNU-extension-free version:

find /var -name somefile.php | while read LINE; do cp /home/me/somefile.php "$LINE"; done

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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