Quick snippet to rename every file within a directory to have a prefix of the directory they reside in as part of the file name. If the directory name has a space in it, replace spaces with underscores for the file name. Run from within the directory in question.
base=$(basename "$PWD"| tr ' ' '_'); for file in *; do [ -f "$file" ] && mv "$file" "${base}_$file"; done
It does the following:
- Gets the name of the current directory, replacing spaces with underscores, and saves into the variable
base - Iterates through everything in the directory in a for loop
- If the item is a regular file, execute the mv command to rename the file to include the contents of the
basevariable as a prefix- It uses BASH substitution to prepend the directory name to the new file name
This was helpful when dealing with a scanning project where many files had the same filename in different directories, which confused stacking images within Immich.