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