Koushik Chandra Koushik Chandra - 1 month ago 6
Bash Question

finding maximum value from a list which is greater than or equal to another value

I have an date in an input file (say fileA) in the format YYYY-MM-DD

e.g. 2016-10-18


Now I have a list of date in timestamp format like below in another file (say in fileB)

20161017120311
20161017140317
20161018010315
20161018160311
20161019020310
20161019124015


Now I want to select only the maximum value of the date (from fileB) which is equal to the date of fileA. So the date which will be selected from fileB in this case will be
20161018160311
.

It can also happen that there is no record in fileB for date
20161018
. Say fileB looks like below

20161017120311
20161017140317
20161019020310
20161019124015
20161020010315
20161021160311


In the case the same code should select the maximum value of the just next available date. i.e. next available date is
20161019
and the maximum value for
20161019
is
20161019124015
. So the output should be in this case
20161019124015

Answer

maxDate.sh:

fileA=$1
fileB=$2
date=`sed s/-//g $fileA`
max=`grep $date $fileB | sort | tail -1`
if [[ $max == '' ]];
then
    date=`sed s/-//g $fileA $fileB | sort | grep $date -1 | tail -1 | egrep -o [0-9]{8}`; 
    max=`grep $date $fileB | sort | tail -1`
fi
echo $max

Running:

./maxDate.sh fileA fileB