
Bash: Bulk rename some files recursively
How to 'just' rename some of the files in a directory in a bash shell (and in the child directories)
A short entry today. I’m investigating some new behaviour but want to make use of previous work. But I didn’t want everything called find-an-sqs-event.*
.
Using the answers to Rename multiple files based on pattern in Unix and Recursively iterate through files in a directory I was able to put together this command line:
while read line; do mv "$line" $(echo "$line" | sed 's/find-an-sqs-event/body-filter/g'); done < <(find . -name 'find-an-sqs-event*' -type f)
If I only wanted change the names of the files in the current directory I could have used something like for f in find-an-sqs-event; do...
, but then I would need to traverse the directory structure. The find command allows you to search recursively, and using process substitution (done < <(find . -name 'find-an-sqs-event*' -type f)
) forces the output of the find command into the while loop.
A command substitution uses sed
to change find-an-sqs-event
to body-filter
while keeping the name of the directory the file is in, and the existing extension ($(echo "$line" | sed 's/find-an-sqs-event/body-filter/g')
). This command substitution is then used in an mv
command: do mv "$line" $(echo "$line" | sed 's/find-an-sqs-event/body-filter/g');
.