LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   converting string in integer in bash script (http://www.linuxquestions.org/questions/linux-newbie-8/converting-string-in-integer-in-bash-script-560622/)

dziadgba 06-10-2007 08:01 AM

converting string in integer in bash script
 
hello everybody,
I tried the following bash script

Code:

#get number of lines of file nodesAndCoordinates
  lines= wc -l nodesAndCoordinates | gawk  '{print  $1}'

  echo $lines

  echo "done"
  lines=`expr $lines + 1`
  echo $lines

OUTPUT
- 23
-
-done
-1

why does it not give the right value (24)
I suppose that the number 23 is somehow stored in the variable lines as string and not as number. Can that be true? How can I convert variable lines in a number?

any help is appreciated
dzia

druuna 06-10-2007 08:25 AM

Hi,

the lines= wc -l....... part isn't syntactically correct, it should be:

lines="`wc -l nodesAndCoordinates | gawk '{print 23}'`"

Besides that, the above line is strange. The output of the wc -l part is discarded (it is given to gawk, but gawk only prints 23) and 23 is printed. I don't know if the output of the wc -l line is actually needed, if not do something like this: lines="23".

Hope this helps.

dziadgba 06-11-2007 06:35 AM

I am sorry: the correct code is

lines= wc -l nodesAndCoordinates | gawk '{print $1}'

and the output would be 23.
The problem however remains the same.
thanks

druuna 06-11-2007 06:50 AM

Hi,

You are still using the wrong syntax:

It should be: lines=`wc -l nodesAndCoordinates | gawk '{print $1}'`
There should be backticks (`) around the statement.

I always surround a declaration with double quotes. I.e:

lines="`wc -l nodesAndCoordinates | gawk '{print $1}'`"

tlinux17 08-31-2009 05:25 PM

for increase a numeric variable, you can use this sintax
lines=$(($lines + 1))
Ciao

chrism01 08-31-2009 05:59 PM

Actually, you don't require the '$' inside the parentheses, in fact you can even do

(( a++ )) # Post-increment 'a', C-style.

http://www.tldp.org/LDP/abs/html/dblparens.html


All times are GMT -5. The time now is 04:41 AM.