'Automator/Apple Script: Move files with same prefix on a new folder. The folder name must be the files prefix

I'm a photographer and I have multiple jpg files of clothings in one folder. The files name structure is:

TYPE_FABRIC_COLOR (Example: BU23W02CA_CNU_RED, BU23W02CA_CNU_BLUE, BU23W23MG_LINO_WHITE)

I have to move files of same TYPE (BU23W02CA) on one folder named as TYPE.

For example:

MAIN FOLDER>

BU23W02CA_CNU_RED.jpg, BU23W02CA_CNU_BLUE.jpg, BU23W23MG_LINO_WHITE.jpg

Became:

MAIN FOLDER>

BU23W02CA_CNU > BU23W02CA_CNU_RED.jpg, BU23W02CA_CNU_BLUE.jpg

BU23W23MG_LINO > BU23W23MG_LINO_WHITE.jpg



Solution 1:[1]

Suggesting oneliner awk script:

echo "$(ls -1 *.jpg)"| awk '{system("mkdir -p "$1 OFS $2);system("mv "$0" "$1 OFS $2)}' FS=_ OFS=_

Explanation:

echo "$(ls -1 *.jpg)": List all jpg files in current directory one file per line

FS=_ : Set awk field separator to _ $1=type $2=fabric $3=color.jpg

OFS=_ : Set awk output field separator to _

awk script explanation

{ # for each file name from list
  system ("mkdir -p "$1 OFS $2); # execute "mkdir -p type_fabric"
  system ("mv " $0 " " $1 OFS $2); # execute "mv current-file to type_fabric"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1