user9006908
user9006908

Reputation: 153

Moving files to subfolders based on prefix in bash

I currently have a long list of files, which look somewhat like this:

Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton
Gmc_W_GCtl_E_Erz_Aue_Dl_254_toe_taixwon
Gmc_W_GCtl_E_Erz_Homersdorf_Dl_201_head_xaubadan
Gmc_W_GCtl_E_Erz_Homersdorf_Dl_262_bone_bainan
Gmc_W_GCtl_E_Thur_Peuschen_Dl_261_blood_blodan
Gmc_W_GCtl_E_Thur_Peuschen_Dl_281_heart_xerton

The naming pattern all follow the same order, where I'm mainly seeking to group the files based on the part with "Aue", "Homersdorf", "Peuschen", and so forth (there are many others down the list), with the position of these keywords being always the same (e.g. they are all followed by Dl; they are all after the fifth underscore...etc.).

All the files are in the same folder, and I am trying to move these files into subfolders based on these keywords in bash, but I'm not quite certain how. Any help on this would be appreciated, thanks!

Upvotes: 1

Views: 848

Answers (2)

Jetchisel
Jetchisel

Reputation: 7791

Using the bash shell with a for loop.

#!/usr/bin/env bash
 
shopt -s nullglob

for file in Gmc*; do
  [[ -d $file ]] && continue
  IFS=_ read -ra dir <<< "$file"
  echo mkdir -pv "${dir[4]}/${dir[5]}" || exit
  echo mv -v "$file" "${dir[4]}/${dir[5]}" || exit
done

Place the script inside the directory in question make it executable and execute it.

Remove the echo's so it create the directories and move the files.

Upvotes: 0

Darkman
Darkman

Reputation: 2981

I am guessing you want something like this:

$ find . -type f | awk -F_ '{system("mkdir -p "$5"/"$6";mv "$0" "$5"/"$6)}'

This will move say Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton into /Erz/Aue/Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton.

Upvotes: 1

Related Questions