Appending the Parent folder Names to the Image File Names in Automator

automatorcommand linefoldersterminal

I have this file structure. I wanted to use the image filename appended with the parent folder names.

Before:

├── ak
│   ├── adak
│   │   ├── Hello\ World456
│   │   ├── cup-printing
│   │   │   └── Tshirt-printing.jpg
│   │   ├── hello-\ world789
│   │   ├── hello-world79
│   │   └── tshirt\ printing
│   │       └── Tshirt-printing.jpg
│   ├── akhiok
│   │   ├── Hello\ World456
│   │   ├── cup-printing
│   │   │   └── Tshirt-printing.jpg
│   │   ├── hello-\ world789
│   │   ├── hello-world79
│   │   └── tshirt\ printing
│   │       └── Tshirt-printing.jpg

Here parent folder names are ak, adak.

Ak= state name
Adak = city name.

After it should be like this..

After:


├── ak
│   ├── adak
│   │   ├── Hello\ World456
│   │   ├── cup-printing
│   │   │   └── Tshirt-printing-adak-ak.jpg
│   │   ├── hello-\ world789
│   │   ├── hello-world79
│   │   └── tshirt\ printing
│   │       └── Tshirt-printing-adak-ak.jpg
│   ├── akhiok
│   │   ├── Hello\ World456
│   │   ├── cup-printing
│   │   │   └── Tshirt-printing-akhiok-ak.jpg
│   │   ├── hello-\ world789
│   │   ├── hello-world79
│   │   └── tshirt\ printing
│   │       └── Tshirt-printing-akhiok-ak.jpg

Bash command can help over here?

In the Automator,

I'm stuck at the finding the all the images of the file name having "tshirt" So I need to find the change the file name to their parent folder.

file name rename with parent folder names

Best Answer

Given your example, and assuming the example holds true, then the example bash code, shown further below, should work.

The following Automator workflow uses the Find Finder Items action, as you have it, but then uses a Run Shell Script action directly after, as there doesn't seem to be a need for a Set Value of Variable action as shown in your OP.

On the Run Shell Script action, set Pass input: to as arguments, as shown in the image below.

Note that the echo command is just there to show what mv command would have been executed to rename the files had it not been there. So, after testing and seeing that the output if formed as wanted, remove the echo command and run the workflow again to actually rename the image files.

Replace the default code in the Run Shell Script action with the following example bash code:

for f in "$@"; do

    dn="$(dirname "$f")"
    fn="$(basename "$f")"
    city="$(awk -F'/' '{print $(NF-2)}'<<<"$f")"
    state="$(awk -F'/' '{print $(NF-3)}'<<<"$f")"

    echo mv "$f" "${dn}/${fn%.*}-${city}-${state}.${fn##*.}"

done

Note: The example bash code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted.


Automator Workflow