Tuesday, August 11, 2015

Oracle and BASH : How to calculate how many minutes have elapsed between two timestamps

There are many ways to calculate minutes passed between two timestamps. The script below is to calculate how many minutes passed between two time stamps using oracle database.

Script : test.sh
====================
#!/bin/bash

# Create a function to accept two timestamps. The order of the timestapms (FROM_TIME, TO_TIME) does not affect the result.
fn_howmany_mins()
{
FROM_TIME=$1
TO_TIME=$2
MINS=`sqlplus -S "/ as sysdba " <<EOF
set echo off
set feedback off
set linesize 10;
set pagesize 0
set trimspool on
set space 0
set truncate on
select abs(round((to_date('$TO_TIME','YYYYMMDD_HH24MISS')-to_date('$FROM_TIME','YYYYMMDD_HH24MISS'))*1440)) from dual;
exit;
EOF`
MINS=`echo $MINS`
echo $MINS
}

#SET up test time stapms as below.
FROM_TIME=20150811_110601
TO_TIME=`date +"%Y%m%d_%H%M%S"`
echo "FROM_TIME=$FROM_TIME TO_TIME=$TO_TIME"

#Call the function to calculate the minutes.
fn_howmany_mins $FROM_TIME $TO_TIME

Sample output sh ./test.sh
==================
FROM_TIME=20150811_111458 TO_TIME=20150811_110601
9

In an actual usage remove the echo statement to get pure number . e.g. number 9 above


Monday, August 10, 2015

Bash : How to get last character in a string

Last character in a string can be extracted using sed. example:-

$cat test.sh
#!/bin/bash
STRING="Humpty Dumpty"
STRING=`echo "$STRING"|sed -e 's/\(^.*\)\(.$\)/\2/'`
echo "STRING=$STRING"
exit 0

Output:-
STRING=y

Thursday, August 6, 2015

How to send select rows into a while loop (bash)

Sample File:-  test.txt
2015-08-01  WHY=Beacuse of testing
DATE=2015-08-01  Beacuse of testing
DATE=2015-08-01  WHY=Beacuse of testing
2015-08-01  Beacuse of testing

Sample script:script.sh
head -3 test.txt|while read LINE
do
echo  "LINE=$LINE"
STR1=`echo $LINE|awk '{print $1}'`
STR2=`echo $LINE|awk '{first=$1; $1=""; print $0}'`

VALU1=`echo $STR1|awk -F\= '{print $2}'`
VALU1="${VALU1:-$STR1}"
LABL1=`echo $STR1|awk -F\= '{print $1}'` 
if [ "$VALU1" == "$STR1" ]
   then
   LABL1=''
   export STR1
fi

VALU2=`echo $STR2|awk -F\= '{first=$1; $1="";print $0}'`
VALU2="${VALU2:-$STR2}"
LABL2=`echo $STR2|awk -F\= '{print $1}'`
if [ "$VALU2" == "$STR2" ]
   then
   LABL2=''
   export STR1
fi
echo "STR1=$STR1 "
echo "LABL1=$LABL1"
echo "VALU1=$VALU1"
echo -e "\t\tSTR2=$STR2 "
echo -e "\t\tLABL2=$LABL2"
echo -e "\t\tVALU2=$VALU2"
echo -e "\n\n"
done

Sample Output:-
LINE=2015-08-01  WHY=Beacuse of testing
STR1=2015-08-01 
LABL1=
VALU1=2015-08-01
STR2= WHY=Beacuse of testing 
LABL2=WHY
VALU2= Beacuse of testing



LINE=DATE=2015-08-01  Beacuse of testing
STR1=DATE=2015-08-01 
LABL1=DATE
VALU1=2015-08-01
STR2= Beacuse of testing 
LABL2=
VALU2= Beacuse of testing



LINE=DATE=2015-08-01  WHY=Beacuse of testing
STR1=DATE=2015-08-01 
LABL1=DATE
VALU1=2015-08-01
STR2= WHY=Beacuse of testing 
LABL2=WHY
VALU2= Beacuse of testing