Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename files in current directory and its subdirectories using bash script?

I'm able to use the 'rename' command to add the missing character to all filenames in the current directory like this:

echo "Renaming files..."
rename -v "s/^abcd124(.+)/abcd1234$1/" *.wav.gz;
echo "Done."

However, I'd like to do this for the current directory and all its subdirectories. I tried this:

echo "Renaming files..."
for dir in $(find ./ -type d); do
    rename -v "s/^$dir\/abcd124(.+)/$dir\/abcd1234$1/" *.wav.gz;
done;
echo "Done."

However, if the $dir variable contains any of these special characters: {}[]()^$.|*+?\ then they are not escaped properly with \ and my script fails.

What would be the best way to solve this problem? Also, what do you guys think of using awk to solve this problem (advantages/disadvantages?)

like image 454
bumbleshoot Avatar asked May 10 '12 23:05

bumbleshoot


2 Answers

You can also try:

find . -name "*.wav.gz" | xargs rename -v "s/abcd124*/abcd1234$1/"

It works on newer Unix systems with "xargs" command available. Note that I edited the regular expression slightly.

like image 158
fredk Avatar answered Sep 21 '22 23:09

fredk


Try:

find ./ -type d -execdir rename -v "s/^abcd124(.+)/abcd1234\1/" *.wav.gz ";"

Find does already provide an iterator over your files - you don't need for around it or xargs behind , which are often seen. Well - in rare cases, they might be helpful, but normally not.

Here, -execdir is useful. Gnu-find has it; I don't know if your find has it too.

But you need to make sure not to have a *.wav.gz-file in the dir you're starting this command, because else your shell will expand it, and hand the expanded names over to rename.

Note: I get an warning from rename, that I should replace \1 with $1 in the regex, but if I do so, the pattern isn't catched. I have to use \1 to make it work.

Here is another approach. Why at all search for directories, if we search for wav.gz-files?

find . -name "*.wav.gz" -exec rename -v "s/^abcd124(.+)/abcd1234\1/" {} ";"
like image 33
user unknown Avatar answered Sep 21 '22 23:09

user unknown