Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Shell scripting -Casting a string into a number

Options
  • 04-09-2008 3:16pm
    #1
    Registered Users Posts: 5,580 ✭✭✭


    Short Question but i cant figure out...


    I have a string , $RNC with a value of "RNC01"

    I want to make it into just the number 1.

    Tried doing this...

    y= 'expr 0 + $RNC'


    This doesnt work. Is there a way of doing this (other than using nawk)?


Comments

  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    What about $RNC = $RNC * 1 ?

    Actually I don't know what your trying to do? - Can you explain bit more.

    $RNC = 1 :confused:


  • Registered Users Posts: 5,580 ✭✭✭veryangryman


    Ok.

    I have a string that contains letters and a number (e.g. RNC01)

    I want it to just contain the numbers so that i can do mathematical operations on it.

    So i can do an if statement later on to check if its value is greater than 6.

    Hope this helps


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    I don't know what shell you are working with but could you not use regular expression substitution to replace all none numbers to nothing so you end up with the a number and then it might be possible to do math operations on it though it still a string - I amn't sure - I don't know if there is any such thing as casting in shelling scripting either.

    Worth a try I guess -


  • Registered Users Posts: 6,509 ✭✭✭daymobrew


    Use sed.
    # Displays RCN01
    echo "RCN = $RCN"
    
    # Extract numbers into a new variable.
    numonly=`echo $var1 | sed 's/[^0-9]//g'`
    
    # Add to the variable and display result (13)
    y=`expr 12 + $numonly`
    echo $y
    


  • Registered Users Posts: 1,228 ✭✭✭carveone


    I have a string , $RNC with a value of "RNC01"

    I want to make it into just the number 1.

    As has been pointed out, there's sed which is the general tool to do this. Are you stuck with expr? expr can use regexps too, albeit in an odd way..

    y=`expr $RNC : '\([0-9]+$\) + 0`

    might work (can't try it myself at the moment)


  • Advertisement
Advertisement