Say I'm in a directory and I want to add a hash to each file in that directory and all sub-directories and add the hash into the filename.
ie:
filename.extension
to
filename.hashcode.extension
search -> perform hash -> use returned hash to rename file
Is there an idiomatic way of recursively doing operations like these in BASH?
I reposted this on StackOverflow LINK
The chosen answer was:
#!/bin/bash
if (("${#}" != 1)) || ! [[ -d "${1}" ]]; then
echo "Usage: $0 /path/to/directory"
exit 1
fi
is_hash() {
md5="${1##*.}" # strip prefix
[[ "${md5}" == *[^[:xdigit:]]* || "${#md5}" -lt 32 ]] \
&& echo "${1}" || echo "${1%.*}"
}
while IFS= read -r -d $'\0' file; do
read hash junk < <(md5sum "${file}")
basename="${file##*/}"
dirname="${file%/*}"
pre_ext="${basename%.*}"
ext="${basename:${#pre_ext}}"
# File already hashed?
pre_ext=$(is_hash "${pre_ext}")
ext=$(is_hash "${ext}")
mv "${file}" "${dirname}/${pre_ext}.${hash}${ext}" 2> /dev/null
done < <(find "${1}" -path "*/.*" -prune -o \( -type f -print0 \))