Home Ask Login Register

Developers Planet

Your answer is one click away!

Nopporn Phantawee February 2016

How to make rename(mv) command recursive

I'm using the following code to rename all of my files in a single directory.

for file in *.* ; do mv "$file" "Add_$file" ; done

How to make it do this operation recursively, i read some topic about using "find with Bash -c" to do this, but don't know how to combine them ?



user unknown February 2016

The first ideas with find don't work, because {} returns ./ with the command:

find . -type f -name "*.*" -execdir mv {} Add_{} ";"

We need something, which removes the ./ in front but works in subdirectories too.

echo 'f=$(basename "$1"); mv "$f" Add_"$f";' > adhoc.sh
chmod a+x adhoc.sh
find . -type f -name "*.*" -execdir $PWD/adhoc.sh "{}" ";"

At least this works for gnu-find. Other finds might not have an -execdir command.

Thanks for skyking for pointing my error out.

For Linux, you might find a version of 'rename' in the repository, but normally it has to be installed and isn't part of the standard installation. If you often rename with the commandline, it is worth the effort. With rename, you specify a regex substitute command and can test it first:

find . -type f -exec rename -n "s/(.*)/Add_\1/" {} ";" 

Post Status

Asked in February 2016
Viewed 1,118 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life