datefor-loopawkaix

AIX: Move file into a year month folder structure using date of file


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

Solution

  • sed can be used as a replacement for the the above case statement:

    FILE_MONTH=`istat $i | grep -w "Last modified:" | awk '{print $5}' | sed 's/Jan/January/g' | sed 's/Feb/February/g' | sed 's/Mar/March/g' | sed 's/Apr/April/g' | sed 's/Jun/June/g' | sed 's/Jul/July/g' | sed 's/Aug/August/g' | sed 's/Sep/September/g' | sed 's/Oct/October/g' | sed 's/Nov/November/g' | sed 's/Dec/December/g'`
    

    Below is the full stack:

    INFORLOG_BKP="/opt/audit"
    for i in `ls ${INFORLOG_BKP}/move`
    do
    FILE_MONTH=`istat $i | grep -w "Last modified:" | awk '{print $5}' | sed 's/Jan/January/g' | sed 's/Feb/February/g' | sed 's/Mar/March/g' | sed 's/Apr/April/g' | sed 's/Jun/June/g' | sed 's/Jul/July/g' | sed 's/Aug/August/g' | sed 's/Sep/September/g' | sed 's/Oct/October/g' | sed 's/Nov/November/g' | sed 's/Dec/December/g'`
    FILE_YEAR=`istat ${INFORLOG_BKP}/move/$i | grep -w "Last modified:" | awk '{print $6}'`
    
    #
    # 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