Search code examples
linuxscriptingcsh

I am unable to type cast string to integer in csh


I want to fetch out '-0.5' from the file example.txt and add 1 to it.

Although I am able to fetch out '-0.5'. but I am unable to add 1 to it, maybe because -0.5 is considered as a string and not a integer.

Code:

#!/bin/csh
set x = `grep Name example.txt | cut -d "|" | -f 5`
echo $x
set y = `expr $x + 1`
echo $y

Obtained Result:

-0.5    
expr: non-numeric argument

Expected Result:

-0.5
0.5

How do I type cast -0.5 to integer?


Solution

  • csh doesn't have types, and everything is a string.

    The problem is that expr only accepts integers: that is, whole numbers. The same applies to csh's built-in @ syntax.

    It's usually better to use bc or dc for this:

    % echo 0.5 + 1 | bc
    1.5
    
    % echo 0.5 1 + p | dc
    1.5
    

    So in your example:

    #!/bin/csh
    set x = `grep Name example.txt | cut -d "|" | -f 5`
    set y = `echo "$x + 1" | bc`
    echo $y