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

I can use the "rename" command to add a missing character to all file names in the current directory, for example:

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

However, I would 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 reset properly with \, and my script does not work.

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

+6
source share
4 answers

You can also try:

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

It runs on newer Unix systems with the available "xargs" command. Please note that I slightly edited the regex.

+6
source

Try:

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

Find already provides an iterator over your files - you don't need for around it or xargs behind, which is often seen. Good - in rare cases, they can be useful, but usually it is not.

It is useful to use -execdir here. Gnu-find has this; I do not know if your find.

But you need to make sure that you do not run the * .wav.gz file in the dir directory, because otherwise your shell will expand it and pass in extended names for renaming.

Note. I get a warning from renaming that I have to replace \ 1 with $ 1 in the regular expression, but if I do this, the pattern will not be found. I have to use \ 1 for it to work.

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

 find . -name "*.wav.gz" -exec rename -v "s/^abcd124(.+)/abcd1234\1/" {} ";" 
+3
source

In bash 4:

 shopt -s globstar rename -v "s/^$dir\/abcd124(.+)/$dir\/abcd1234$1/" **/*.wav.gz; 
+1
source

Just remember that Gentoo Linux has its own rename utility.

http://developer.berlios.de/project/showfiles.php?group_id=413

his ebuild

http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/sys-apps/rename/rename-1.3.ebuild?view=markup

for Debian or possibly Ubuntu,

rename is /usr/bin/prename , which is a perl script

Before moving see rename --help .

+1
source

Source: https://habr.com/ru/post/915457/


All Articles