Bash script to sort files into folder according to a string in the filename

Hi all.

I am very new to linux scripting and i have a task i can only solve with a script.
I need to sort files base on the date string in their filenames and create a folder using the same date string then move the files to their respective folders.

Scenario:
Folder Path: /test/testfiles
Files:
data20120106_101_015118.unl.bz2
data20120107_101_016118.unl.bz2
data20120108_101_015618.unl.bz2
data20120109_101_015118.unl.bz2
data20120109_101_015118.unl.bz2
data20120109_101_015118.unl.bz2
data20120110_101_015118.unl.bz2
data20120110_101_015118.unl.bz2
data20120110_101_015118.unl.bz2
data20120111_101_015118.unl.bz2
data20120111_101_015118.unl.bz2
data20120112_101_015118.unl.bz2
data20120112_101_015118.unl.bz2

I need to create a folder e.g: 20120110 and then move all files containing 20120110 e.g data20120110_101_015118.unl.bz2 into the created folder. I have to do this for several
files as far back as 2010. All files have the same filename format as above.

Thanks for your help.

Try this (not tested):

cd /test/testfiles
for i in data*.unl.bz2
do
   data_ymd=${i%%_*}
   ymd=${data_ymd#data}
   if [ ! -d $ymd ]; then
      mkdir $ymd
   fi
   mv $i $ymd
done
1 Like