Assistance for sorting files

Hi there,

I have tried using the "find" command to do this but to no avail as the "find -mtime" command I used descend to the directories from my current working directory.

Say in "directoryA" has multiple files and those files are created on a daily basis.

Under "directoryB", there are individual directories labelled 01, 02, 03 ....... 31.

What I am trying to achieve here is a BASH script that will perform a loop in "directoryA" sorting those 30 individual files based on modified date and then move those files into their respective directories under "directoryB". For instance, a file named "a1.txt" in "directoryA" that was created on the 1st of Jan is to be moved to the "01" directory under "directoryB".

Any help would be much appreciated. :slight_smile:

This can be done. But the way you have put your question together leaves too much guesswork on our part.

Please give us actual sample input - filenames - and actual expected results.

Thanks for the swift response.

My current working directory:

/home/dirA

has the following files:

a1.txt created on 1st of Jan
a2.txt created on 2nd of Jan
a3.txt created on 3rd of Jan
a4.txt created on 4th of Jan
a5.txt created on 5th of Jan
a6.txt created on 6th of Jan
a7.txt created on 7th of Jan
a8.txt created on 8th of Jan
a9.txt created on 9th of Jan

Expected results:

a1.txt (/home/dirA/a1.txt) to end-up in this directory "/home/dirB/01/" and the long listing of that file is "/home/dirB/01/a1.txt"

#! /bin/bash

$fromDir=/home/dirA
$toDir=/home/dirB

for x in $fromDir/*
do
    new=$(stat -c%y $x | awk -F'[ -]' '{print $3}')
    mkdir $toDir/$new
    cp $fromDir/$x $toDir/$new/
done
2 Likes

stat is not available everywhere. This may be an alternative:

$fromDir=/home/dirA
$toDir=/home/dirB
cd "$fromDir"
LANG=C ls -nl |                               # use POSIX locale for ls command to get universal output
{
  read                                        # discard the "total" line
  while read perm x x x x x day x file        # Read the next entry and catch $1, $7 and $9 and further.
  do
    case $perm in (-*)                        # if it is a file
      new=$(printf "%02d" "$day")             # pad a zero to day if need be
      mkdir "$toDir/$new" 2>/dev/null         # create the target directory; ignore error
      cp -p "$file" "$toDir/$new"
    esac
  done
}
1 Like