Several days ago, I needed to update some of my projects. The changes were mostly the same and needed to be applied to the same files every time. In some cases, I also had to copy certain files to specific directories with the same name. This was a task that could have been done more efficiently and quickly with a script.
To simplify the explanation, let’s say that I wanted to copy the same file to directories with the same name, such as “src”. Our projects were organized as follows:
.
├── project1
│ └── somedir
│ └── src
├── project2
│ └── src
└── project3
└── somedir
└── some other
└── src
I started searching for a solution and found myself tangled in a strange web of for and while loops, as well as exotic uses of the mapfile command. At first glance, these solutions didn’t convince me. Nevertheless, I decided to loop over the mapfile output, using something like the following code:
mapfile -d $'\0' FILES < <(find . -name "src")
and loop the content of the $FILES array. It seemed nice and easy, but something bad was about to happen: one of the directories contained a space. This can be a major problem when iterating through an array in bash.
I started to figure out how to solve this issue, and began to cobble something together. But then I stopped and thought to myself, ‘Wait a minute, it can’t be this difficult to solve such a simple task.’ I knew there was something I was missing, something buried deep in my mind, but I just couldn’t recall it. I don’t know if this happens to you, but at that moment I realized that the solution was probably very easy, and I was only wasting time.
Finally, I decided to do a search on DuckDuckGo (yes, I know, we usually say ‘search on Google,’ but it’s not the only search engine out there!). That’s when I came across this article, and had my ‘aha’ moment - the solution was as simple as I had thought.
find . -name src -exec cp file {} \;
And I obtained:
.
├── file
├── project1
│ └── somedir
│ └── src
│ └── file
├── project2
│ └── src
│ └── file
└── project3
└── somedir
└── some other
└── src
└── file
Of course, my situation was far more complex than this - I didn’t just have to copy a file. However, the purpose of this short story is to help people who, like me, have to perform similar tasks, and to save them from wasting time on something that should be easy.
I hope you enjoyed this post, if you want to share it to your contacts on the social media, you can do it by clicking on the social icons at the beginning of this post, otherwise you can copy the url and share it wherever you like.
If you want to reach me, you will find all my contacts in the About page. Sooner or later I will enable comments on my posts, in the meantime, if you have questions, contact me, I’ll be happy to answer.