Ubuntu – Rename files in subfolders with parent folder names

bashcommand linegnomenautilusscripts

I have a main directory that has four folders f1, f2, f3 and f4 each of these folders has 10 folders, and each of these 10 folders ff1...ff10 has some .jpeg images with some names lets say image1…. and so on. What I want to know is how to rename these .jpeg images in each of these folders of the 10 folders in each of f1, f2, f3 and f4, so that I will concatenate the parent folders in the beginning of its name, for example of image1.jpeg is located in f3/ff1 then its name will be f3_ff1_image1.jpeg, same with all the other images in the other 10 folders in each of the four main folders. If anyone can please advise how this can be done in a .sh file.

Best Answer

With a loop and some bash string manipulations

while read -rd $'\0' f; do 
  d="${f%/*}"; p="${d/\//_}";
  echo mv -- "$f" "${d}/${p}_${f##*/}"
done < <(find -type f -name '*.jpeg' -printf '%P\0')

(remove the echo once you've confirmed it matches the files correctly)

With the perl-based rename command and bash globstar

shopt -s globstar
rename -nv -- 's|(f\d+)/(ff\d+)/(image\d+)|$1/$2/$1_$2_$3|' **/*.jpeg

(remove the -nv once you've confirmed it matches the files correctly)