Hi,
I am trying to do an addition to a value stored in a variable...
var1=`grep -n "match" sample.txt|cut -d : -f1`
var2=`echo $var1|cut -d " " -f1`
(Here i want add +1 to the output value)
Hi,
I am trying to do an addition to a value stored in a variable...
var1=`grep -n "match" sample.txt|cut -d : -f1`
var2=`echo $var1|cut -d " " -f1`
(Here i want add +1 to the output value)
echo $var1|cut -d " " -f1 | xargs echo "1 +" | bc
or
awk '{print $1+1}' <<< $var1
there are many ways to do it.
--ahamed
var2=`expr $var2 + 1`
Do you need the contents of var1, or is it just a work variable needed to get the value you want to put into var2? If you just want var2 to be 1 plus the line number of the 1st line in sample.txt that matches the basic regular expression match
, calling awk once instead of grep once and cut twice is probably faster:
var2=$(awk '/match/{print NR + 1; exit}' sample.txt)
but note that when using awk, match
is treated as an extended regular expression instead of a basic regular expression. As always, if you're running on a Solaris/SunOS system, use /usr/xpg4/bin/awk
or nawk
instead of awk
.
If you do need the complete list of matching lines, you can keep the way you're currently setting var1, but set var2 just using standard shell parameter expansions:
var2=$((${var1%% *} + 1))
This should be MUCH MUCH faster than calling cut, xargs, and bc; awk; or cut and expr. This won't work with the original Bourne shell, but works with any POSIX conforming shell (such as bash or a 1993 or later version of ksh).