Getting month older

I need month older lines from a file

file
1        666      2013-08-23    04:24:11     
33       543     2013-06-11    18:04:20     
33       413     2013-06-20    1:40:54 
1        776      2013-08-20    18:04:21     
.0       877      2013-08-21    05:50:04     

I'm checking older lines from third field, if it is older than 30 days delete the line and before deleting save the second field of the line to another file.

Output:
new.file
543
413
 
file
1        666      2013-08-23    04:24:11     
1        776      2013-08-20    18:04:21     
.0       877      2013-08-21    05:50:04    

I'm using the below one..

awk -v cudate=`date "+20%y%m%d"`  '{line=$0; dateval=$3;FS="-"; $0=dateval;  thisdate=$3*10000+$1*100+$2; if (thisdate>cmpdate) print line; FS=" ";}' file 

Need GNU date command:

#! /bin/bash
d=$(date -d "-30 days" +%Y%m%d%H%M%S)

awk -v d=$d '{split($3,a,"-");split($4,b,":")
    s=sprintf("%04d%02d%02d%02d%02d%02d",a[1],a[2],a[3],b[1],b[2],b[3])
    if (s<d) { print $2> "outputfile1"}
    else {print > "outputfile2"}
    }' file
echo mv outputfile2 file

if command is right, remove the red echo

Thanks....
But I'm using KSH. GUN date command is throwing error.

-d

option is not working

If your ksh is ksh93 you can also use the builtin date formatting capability:

d=$(printf "%(%Y%m%d%H%M%S)T" "30 day ago")

To check for ksh93 just use

print $KSH_VERSION

If the output is not empty, you have ksh93.

1 Like

No, Not using ksh93

What OS and version are you on?

OS: HP-UX
Version: U
Release:0.58

If you have perl available, this script might help

#!/usr/bin/perl

use POSIX qw(strftime);
my $d = time () - 30 * 24 * 60 * 60;
my $s = strftime "%Y%m%d%H%M%S", localtime ($d);
print $s;

Save the script as, lets say 30daysago (don't forget to chmod +x 30daysago ) and then use

d=$(./30daysago)

If it's a calendar month, then you can simply:-

#!/bin/ksh
typeset -Z2 MM DD
date "+%Y %m %d" | read Y4 MM DD

((MM=$MM-1))
if [ $MM -eq 0 ]
then
   MM=12
   ((YY=$yy-1))
fi

echo "Date last month was $DD $MM $Y4"

Does this help? I would be concerned about just taking off 30 days as suggested earlier. On 1st March, this will report either 30th or 31st January. :eek:

Robin
Liverpool/Blackburn
UK