问题
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:
- Read the line from text file,
- If the date value of this line is older than 50 days,
- then read the line till before the underscore character e.g. TEST1 into a variable,
- and then remove this line.
The variable will be used for removing the user from database. Any help would be appreciated.
回答1:
There is a dateconv
command that converts dates to number of seconds since the epoch; you could use that to determine whether a date is N seconds (the number of seconds in fifty days) older than the current date. However, dateconv
is not universally available.
You would use dateconv
as follows:
dateconv -i %Y%m%d -f %s
and similarly to find the number of seconds since epoch of the current date; you would then use the shell builtin expr
to determine whether that date were 50*24*3600
seconds older than the current date.
The next best bet is to use Perl.
回答2:
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
来源:https://stackoverflow.com/questions/38211373/use-ksh-to-parse-a-name-and-a-date-from-a-line-and-remove-the-line-if-the-date-i