'Rename all files in a directory to be the same as the directory

I have a folder called "tokens". In this folder, I have several other folders, called things like "guard", "noble", "assassin", etc. In those folders are image files with varying names and file formats.

I would like to run through the all the folders and files in "tokens", and rename each file to be whatever directory it is in with a number appended to it. So, a file in the "guard" folder would be named "guard0001.jpg", and the next would be "guard0002.png", for instance.



Solution 1:[1]

There are certainly better/faster approaches but this should do the trick.

find tokens -type f -exec sh -c "path='{}'"'; file="${path##*/}"; dir="${path%/*}"; folder="${dir##*/}"; echo mv "$path $dir/$folder$file"' \;

Remove the echo when you're satisfied with the output it produced.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1