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
Good news everyone! The Boards.ie Subscription service is live. See here: https://subscriptions.boards.ie/

Shell scripting -Casting a string into a number

  • 04-09-2008 03:16PM
    #1
    Registered Users, Registered Users 2 Posts: 5,746 ✭✭✭


    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, Registered Users 2 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, Registered Users 2 Posts: 5,746 ✭✭✭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, Registered Users 2 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, Registered Users 2 Posts: 6,631 ✭✭✭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, Registered Users 2 Posts: 1,346 ✭✭✭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