I am trying to create a folder structure for audit logs that gets generated by the AIX system and Database
Below is a simple example of a file in a folder:
ls -l /opt/audit/move/
Output:
-rw-r--r-- 1 gl_user user 0 18 Aug 2019 test1.txt
-rw-r--r-- 1 gl_user user 0 06 Nov 18:55 test2.txt
The problem with the above ls -l command is that recent files in column 8 displays time instead of the year. I could of used awk and a for loop to get the month and year for the file, but this is not an option as seen above
The idea is to move the files in the below folder structure:
# ls -l /opt/audit/2019/August/test1.txt
-rw-r--r-- 1 gl_user user 0 18 Aug 2019 test1.txt
# ls -l /opt/audit/2022/November/test2.txt
-rw-r--r-- 1 gl_user user 0 06 Nov 18:55 test2.txt
CodePudding user response:
This method involves using istat with a for loop to get the month and year of the file from the last modified date. This does work, but I would like to know if there is a better or shorter method to achieving what I want:
INFORLOG_BKP="/opt/audit"
for i in `ls ${INFORLOG_BKP}/move`
do
FILE_MONTH=`istat ${INFORLOG_BKP}/move/$i | grep -w "Last modified:" | awk '{print $5}'`
FILE_YEAR=`istat ${INFORLOG_BKP}/move/$i | grep -w "Last modified:" | awk '{print $6}'`
case $FILE_MONTH
in
Jan) MONTH_STRING=January
;;
Feb) MONTH_STRING=February
;;
Mar) MONTH_STRING=March
;;
Apr) MONTH_STRING=April
;;
May) MONTH_STRING=May
;;
Jun) MONTH_STRING=June
;;
Jul) MONTH_STRING=July
;;
Aug) MONTH_STRING=August
;;
Sep) MONTH_STRING=September
;;
Oct) MONTH_STRING=October
;;
Nov) MONTH_STRING=November
;;
Dec) MONTH_STRING=December
;;
esac
#
# Create directory if it does not exist
#
[ -d ${INFORLOG_BKP}/${FILE_YEAR}/${MONTH_STRING}/ ] || mkdir -p ${INFORLOG_BKP}/${FILE_YEAR}/${ MONTH_STRING}/
mv ${INFORLOG_BKP}/move/$i ${INFORLOG_BKP}/${FILE_YEAR}/${MONTH_STRING}/
done
CodePudding user response:
One idea using ksh93
(for associative array support):
typeset -A months=( [Jan]="January" [Feb]="February" ) # OP can fill in the rest of the array
for fname in "${INFORLOG_BKP}"/move/*
do
read -r mon3 year < <(istat "${fname}" | awk '/Last modified:/{print $5,$6}')
tgtdir="${INFORLOG_BKP}/${year}/${months[$mon3]}"
mkdir -p "${tgtdir}" # '-p' also says to *not* print an error msg if dir already exists
mv "${fname}" "${tgtdir}"
done