I'm trying to change the names of multiple files recursively within a directory, looking something like this:


Because a tool that I'm using won't recognize wildcards, I would like to remove the text from each file ending in '1.txt', such that each instance matches exactly.

I can generate a list of those files to STDOUT and pipe it somewhere with:

find . -name '*1.txt' -print0 |

...But I'm not sure how to write the regular expression that (I assume) exists to rename the files. Additionally, rename is not installed with my setup, and I don't have the permissions to add it.


1 Answer 1


You can use your find statement in a for loop and use shell substring replacement. Something like this.

for file_name in $(find . -name '*1.txt' -print0); do
    #echo mv -v "$file_name" "${file_name/substring_to_be_replaced/the_replacement_substring}"
    mv -v "$file_name" "${file_name/substring_to_be_replaced/the_replacement_substring}"

Just put your values in substring_to_be_replaced and the_replacement_substring. For more information how to replace a substring look here https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script.

And use the commented out echo statement first to make sure your substring substitution and find work correctly. When you are sure everything is fine, comment out echo and use the actual mv statement. Once you start mv with wrong parameters it is very difficult or even impossible to undo.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .