Unix & Linux Asked by bactro on November 6, 2021
I’m trying to copy a single file to all of the deepest subdirectories in a tree structure. Imagine it looks like this:
bar
dir1
| |
| +--dir2
| |
| +--dir3
| +--dir4
| |
| +--dir5
| +--dir6
| |
| +--dir7
I want "bar" to be copied only to the deepest subdirectories, like this:
bar
dir1
| +--dir2
| |
| +--dir3
| |
| +-- bar
| +--dir4
| |
| +--dir5
| |
| +-- bar
| +--dir6
| |
| +--dir7
| |
| +-- bar
I’m not sure how to approach this, since files end up in middle directories sometimes, but I can’t find a way to target the deepest subdirectories.
Edit: my attempt at solving this. This copies to all directories inconsistently, still for some reason, not just the deepest ones.
find . -exec cp -r bar {} ; -type d -links 2
Solution: On the directory containing bar
,
find . -type d -links 2 -exec cp bar {} ;
Your original attempt
find . -exec cp -r bar {} ; -type d -links 2
contains no syntactic errors, but does not behave as you expected. Because -exec
comes before the -type
and -links
filters, the filters never apply and exec
gets everything under (and including) the current directory, not only regular files but also directories. If you are not convinced, check the output of
find . -exec echo X{}X ; -type d -links 2 -exec echo Y{}Y ;
You will see that all the files get listed between two X
, but only only the correct dir{3,5,7}
files between two Y
. That explains why bar
popped up in middle directories too.
Also, the -r
option activates recursive copies. Since what is being copied is a regular file (bar
), -r
is not needed.
Answered by Quasímodo on November 6, 2021
You can use:
find . -type d -links 2 -exec cp file {} ;
It will find directories having 2 hard links, and then copy your file to that particular directory.
Answered by Prvt_Yadav on November 6, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP