Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Replace a string in file names recursively in Linux

Use this simple BASH script to recursively rename parts of file names in Linux.

Finding some simple but reliable code to perform this task has been a challenge. As always with Linux, there are many ways to achieve this outcome, but I have found this method to be reliable.

In my example, I have multiple image files for which I need to have the string “White Peas” replaced with “Peas” in their file names.

This can be achieved with the following code:

find . -type f -name "* Peas*" -exec bash -c 'mv "$0" "${0//White Peas/Peas}"' {} \;

The first part of the command uses the find function to look for any files with ” Peas” in the file name (note the space because I am actually searching for a whitespace character and then the word). The second part then uses the mv function to find “White Peas” and replace it with “Peas”.

This could be summarised as:

find . -type f -name "[SEARCH STRING]" -exec bash -c 'mv "$0" "${0//[FIND TEXT]/[REPLACE TEXT]}"' {} \;

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.