Question : BASH Script to copy files based on the filename

I'm sure this answer exists somewhere but I can't seem to find it, so I'm sorry about that.

I have many files that need to be sorted to different directories based on the filename. Here are a few examples of the filenames

543580_080216_1017_Z_JrPom_D
543580_080216_1020_A_Y1D1_AC
543580_080216_1020_E_YS2DI_F
543580_080216_1020_Z_JrHH_DM
543580_080216_1023_B_Y1DII_E
543580_080216_1023_D_YS2DII_
543580_080216_1023_F_YL2_Orl

I need to copy the files with a "_Z_" in them to directory "Z", files with "_A_" to directory "A", etc.

I'm sure the script is simple, I just need some guidance. Thanks

Answer : BASH Script to copy files based on the filename

#!/bin/bash

# So you are in bash.

cd dir-that-has-the-files
mkdir ../sorted-dirs
for file in $(ls -1 *_*_*_*_*)  # or just * if you know all the files in here are subject
do
  dir=$(echo $file | cut -f4 -d'_')
  destdir=../sorted_dirs/$dir
  mkdir -p $destdir
  cp -a $file $destdir
done

Random Solutions  
 
programming4us programming4us