Announcement

Collapse
No announcement yet.

incremental loop

Collapse
This topic is closed.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    incremental loop

    Dear friends

    say i have a file like

    1
    2
    3
    5
    8
    9
    16
    17
    35
    36
    .
    .
    ..
    till 50

    now I ask user to give a input between 1 to 50.
    now there are two condition
    First: if the number is found in file then script should display the number --------------- no problem grep woks it for me
    Second: but problem is this if the number given by user; does not found in the file then script should display the very next no to the screen. like say

    echo " give a number between 1 to 50 " # user gives 5 !!! then script should display $read1
    # if user gives 10 then script should display the very next no to 10 is 16.............

    please help me ........

    thanks to you all

    #2
    I assume you're scripting in bash. I suggest loading the file into a bash indexed array; then you can look it up with a for loop.

    Say your file is "numbers.txt", and the user has input "num":
    Code:
    arr=($(<numbers.txt))
    for (( i=0; i < ${#arr[*]}; ++i )); do
        (( arr[i] >= num )) && break;
    done
    echo The first number on or after $num is ${arr[i]}
    Regards, John Little

    Note you'd want to handle going off the end, that would be i == ${#arr[*])
    Last edited by jlittle; Apr 01, 2013, 05:33 AM.
    Regards, John Little

    Comment

    Working...
    X