If grep value is null then assign 0 to variable

DELETE=`cat $logfile1 | egrep -i "Delete" | sed 's/  */ /g' | cut -d" " -f2`

INSERT=`cat $logfile1 | egrep -i "Insert" | sed 's/  */ /g' | cut -d" " -f2`  

UPDATE=`cat $logfile1 | egrep -i "Update" | sed 's/  */ /g' | cut -d" " -f2`    

I need soming like below:

if value is null then INSERT=0

Regards,
Veera

Veera,

Kindly let us know the input file with expected output on same.

Thanks,
R. Singh

Static words to grep:

Insert
update
delete
fieldcomp
lob
After Images

File content:

SCOTT.TEMP_TBL                                     Partition 4
Total Data Bytes             26084
  Avg Bytes/Record             326
Insert                           8
FieldComp                       72
After Images                    80

output:


Insert|update|delete|fieldcomp|lob|After Images

8|0|0|72|0|80

Regards,
Veera

akshay@nio:/tmp$ cat static_word 
Insert
update
delete
fieldcomp
lob
After Images
akshay@nio:/nio$ cat file
SCOTT.TEMP_TBL                                     Partition 4
Total Data Bytes             26084
  Avg Bytes/Record             326
Insert                           8
FieldComp                       72
After Images                    80
akshay@Aix:/nio$ awk 'FNR==NR{B[A[FNR]=$0]=0;next}{for(i in A)if(match(tolower($0),tolower(A)))B[A]=$NF}END{for(i=1;i<=length(A);i++){ h = h ? h OFS A : A; d = d ? d OFS B[A] : B[A] } print h RS RS d }' OFS='|' static_word  file

Resulting

Insert|update|delete|fieldcomp|lob|After Images

8|0|0|72|0|80

Is it possible without awk and sed. as its needs to run with commands (not advanced like awk) in environment.

How about

DELETE=$(grep -Eic "Delete") $logfile1  

etc...

Hi Rudi, Your code results if value is null then count is 0.

I also need if static word exist in file,place the value.

Based on your code, below came in my mind.

while read line 

do 

if [ $(grep -ic "$line"  testgg.qa.txt1) -ne 0 ]; then
Delete=`cat testgg.qa.txt1| egrep -i "Delete" | sed 's/  */ /g' | cut -d" " -f2`
else
Delete=0
fi

done < static_file

I m trying if I can get it in single line and assign to variable.
Regards,
Veera

The following works with all Posix shells

ins=0
del=0
upd=0
a_i=0
set -f
while read line
do
  set -- $line
  eval lastA=\$$#
  case `echo "$line" | tr '[:lower:]' '[:upper:]'` in
  INSERT*) ((ins=ins+lastA));;
  DELETE*) ((del=del+lastA));;
  UPDATE*) ((upd=upd+lastA));;
  "AFTER IMAGES"*) ((a_i=a_i+lastA));;
  esac
done <"$logfile1"
set +f
echo "INSERT=$ins"
echo "DELETE=$del"
echo "UPDATE=$upd"
echo "AFTER_IMAGES=$a_i"

Actually, you need some extensions to POSIX requirements to process the above script. The current standard specifies the behavior of $((expression)) , but not the behavior of ((expression)) . ( ksh88 does not support ((expression)) .)

To be portable to any POSIX shell, lines like:

  INSERT*) ((ins=ins+lastA));;

would have to change to something like:

  INSERT*) ins=$((ins+lastA));;
1 Like