Script to move files to a directory according to date

hi all,

here is the description to my problem.

input parameter: $date1

based on the date i need to select three files starting with audit.log* based on its modified date, a date before, a date after(if its exists). We need to compare the input date to modified date of the file. And then move these three files to a directory.

can u please help me in writing the code to select the multiple files based on the date input.

An example of how a ls -lrt looks like.

-rwx--r--r oracle oinstall 4354334 Aug 24 10:13 ois_audit.log.20110824.3445543.9090899
When i do a ls --full-time

-rw-r--r-- 1 oracle oinstall 52428553 2011-08-16 15:13:44.000000000 -0700 ois_audit.log.20110816.221344.336078

i need it urgently for the delivery of the code.

Any help is highly appreciated.

Thanks,
Chandu

The first question is, which format $date1 has. It needs to be in seconds-since-epoch.
If it is a string, convert it with

date1=`date -d "$date1" +%s`

Then

export date1
files_to_save=`ls -ltr --time-style=+%s | awk 'function abs(x){return x<0 ? -x : x}BEGIN{date1=ENVIRON["date1"]}{print abs($(NF-1)-date1)"\t"$NF}' | sort -n -k1,1 | head -3 | cut -f 2`;

I can give date1 in any format i like. I can mention it as MMDDYYYY
Can you explain how the code works...
do i have to save the first code in a separate file called date1 and export it?
Also it does not have a (date1+1)next day.

Thanks for your response.

Proposal: Give date1 as "YYYY-MM-DD HH:MM". The script would then be called as:

./myscript.sh "YYYY-MM-DD HH:MM"

(if such precision not necessary, simply drop the HH:MM) and contains:

export date1=`date -d "$1" +%s`
files_to_save=`ls -ltr --time-style=+%s | \
awk 'function abs(x){return x<0 ? -x : x}BEGIN{date1=ENVIRON["date1"]}{print abs($(NF-1)-date1)"\t"$NF}' | \
sort -n -k1,1 | head -n 3 | cut -f 2`

What it does is to convert the date argument ($1) to seconds-since-epoch format
pass it as environment variable date1 inside the awk script,
which receives the output from the ls command as standard input.
The second-to-last column contains the file modification time as seconds-since-epoch
(epoch = 1970-01-01 00:00 GMT), the last column contains the filename.
These two columns are taken, from the timestamp the absolute difference
to your date argument (converted to seconds-since-epoch) is calculated,
so first column contains this absolute time difference, the second one the filename.
Then it is numnerically sorted according to the first column, i.e. the filenames with
the three smallest time differences appear in the first three lines, which are taken
by "head -n 3" and then only the second column of these three lines is taken
by "cut" to stay only with the filenames.
Finally you may add the following two lines to the script
in order to create a directory with a unique name and copy the files to it:

mkdir -p $date1
cp $files_to_save $date1
1 Like