Find the answer to your Linux question:
Results 1 to 2 of 2
In the code below I'M trying to add a 00 to the left side of the NUM if NUM is 1 digit, e.g. input 4 -> 004 and to add ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Newbie
    Join Date
    Dec 2010
    Posts
    122

    adding a string to a number/string


    In the code below I'M trying to add a 00 to the left side of the NUM if NUM is 1 digit, e.g. input 4 -> 004 and to add single 0 to NUM if NUM is 2 digits, e.g. 45 -> 045. Any ideas on how to accomplish that?

    Code:
    #!/bin/bash
    
    read -p "Enter a number no higher than the billions range" NUM
    
    NUMBEROFDIGITS=${#NUM}
    NUMBEROFGROUPS=$( expr ${NUMBEROFDIGITS} / 3 )
    
    if [[ ${NUMBEROFDIGITS} -lt 3 ]]; then # {
        NUMBEROFGROUPS=1
        if [[ ${NUMBEROFDIGITS} -eq 2 ]]; then # {
            NUM="0"+"${NUM}"
            echo ${NUM}
        else # } {
            NUM="00"+"${NUM}"
            echo ${NUM}
        fi #}
    elif [[ `expr ${NUMBEROFDIGITS} % 3` -ne 0 ]]; then # } {
        let NUMBEROFGROUPS=NUMBEROFGROUPS+1
    fi # }
    
    echo "Number of groups is: ${NUMBEROFGROUPS}"
    #END

  2. #2
    Linux Enthusiast
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    651
    See the answer in your old thread (or is this a class assignment) because this already has shown up in another thread.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •