user6027133 user6027133 - 4 months ago 10
Bash Question

Use ksh to parse a name and a date from a line and remove the line if the date is older than 50 days

I have a test file with the following format, It contains the username_date when the user was locked from the database.

$ cat lockedusers.txt
TEST1_21062016
TEST2_02122015
TEST3_01032016
TEST4_01042016
$


I'm writing a ksh script and faced with this difficult scenario for my level of scripting. What I would like to do is:


  1. Read the line from text file,

  2. If the date value of this line is older than 50 days,

  3. then read the line till before the underscore character e.g. TEST1 into a variable,

  4. and then remove this line.



The variable will be used for removing the user from database. Any help would be appreciated.

Answer

veryone, thanks for your help - here's the solution for this problem not including how to remove users from teh database buyt it should be easy to figure out for anyone as this code will generate the user list that are older than 50 days.

#!/bin/ksh
echo
cat test |
while IFS="_ " read LUSER LDATE
do
        Day=`echo $LDATE | cut -c1,2`
        Mon=`echo $LDATE | cut -c3,4`
        Year=`echo $LDATE | cut -c5-8`
        Date=`echo $Mon/$Day/$Year`
        if [[ $(( $(date +%s) - $(date +%s -d${Date}) )) -ge 4320000 ]] ; then
        #echo "$LUSER, $LDATE"i
        echo "$LUSER" >> userRemovalList
        grep -v "$LUSER" test > temp && mv temp test
        fi
done
chmod 755 userRemovalList

Credit to my colleague Derek another helpers from UNIX helper portal http://www.unix.com/shell-programming-and-scripting/267002-ksh-read-line-parse-characters-into-variable-remove-line-if-date-older-than-50-days-2.html#post302977045