DEV Community

Maciek Chmura
Maciek Chmura

Posted on

6 2

Bash magic spell to replace files

bash

Most recently, at my work project, I assigned myself to a task to replace a png file across the project with new graphics.
Same file name, different pixels.

A quick search for the file in VSCode showed around 35 results across different folders.

But why there are 35 copies of the same png in the project?

Good question for which I have no answer πŸ€”

What a can be done here to complete the task?

  1. Manually track all the files in file explorer and replace them. This can take around 15 to 25 minutes depending if you double check copies and how fast you click... boooooring!

  2. Or find a bash command to do the work for you.

Challenge accepted!
What should be done?

  • have a reference to file with new data

  • find the file by name

  • replace found file with new data

  • repeat until all files in the folder are changed

After some googling, reading stack overflow and MAN pages, I stitched this line to replace a file with new data:

find . -print -type f -name apple.PNG -execdir cp /mnt/c/Users/Maciej_Chmura/replace_source/orange.PNG {} \;

Let's break it down to know exactly what is happening:

find πŸ‘‰ bash find command
. πŸ‘‰ current execution context, current folder
-print πŸ‘‰ log the process
-type f πŸ‘‰ specify to look for files
-name file_name πŸ‘‰ specify file name to search
-execdir πŸ‘‰ execute command from the subdirectory
cp from_file to_file πŸ‘‰ copy from one file to another
{} πŸ‘‰ is a placeholder for file that `find` will find

Don't stop here, learn more about these commands:

find
cp

With this little line, all files in the current folder and subfolders will be replaced.

After this research, I thought of another use case.
What if you need to rename the file?
The command is almost the same:

find . -print -type f -name apple.PNG -execdir mv {} orange.PNG \;

Hopefully, this will save you some time in the future when encountered in a similar case.

Do you know any magic bash spells?

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
maciekchmura profile image
Maciek Chmura β€’

cool tip :D thanks

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free