Rename files in subfolders by adding "_ParentFolderName"

You can create an Automator Quick Action/Service with a Run Shell Script action using the settings as shown in the image further below, and by replacing the default code in the Run Shell Script action with the following shell script code:

Example shell script code:

for d in "$@"; do
    [ -d "${d}" ] || continue
    while IFS= read -r l; do
        mv "${l}" "${l%.*}_${d##*/}.${l##*.}"
    done < <(find "${d}" -type f \! -name '.*')
done

Notes:

To use the Automator Quick Action/Service, in Finder select the ParentFolder(s) containing the subfolders and the files within them you want renamed with the name of the ParentFolder added to them, and then right-click and select e.g. Add ParentFolderName to Files from the Quick Actions or Services context menu.

The example shell script code, shown above, was tested as an Automator Service/Quick Action under macOS Catalina and with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.

  • 1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.

If the settings in the Automator Quick Action/Service are set as shown in the image below, then technically [ -d "${d}" ] || continue is not really needed, however it also doesn't hurt to have it in the code as it just ensures what being passed is a directory. Just consider it as error handling.

Pay attention to the settings shown in the image below of the Automator Quick Action/Service.

enter image description here