Alireza Oliya
Alireza Oliya

Reputation: 34

Reading numeric terminal input into an array and sorting the array [Bash]

I've been trying to read numeric input from the terminal in Bash (Two separate approaches. First is directly entering numbers into the CLI and second reading the numbers from a file) and saving it in an array, sorting the array and showing the result. (The original problem stated that the input is saved in an array and then sorted)

I don't know if it's better to save it in a file and sort the values in the file or directly the input from the terminal into the array and sorting it afterwards. I have searched for both methods.

Thank you.

P.S. I've read many sources and links but unfortunately I couldn't come across a solution. I've tried using loops and prompting the user in asking how many numbers they want to feed in as the input but it was doomed to failure.

Upvotes: 1

Views: 175

Answers (2)

tshiono
tshiono

Reputation: 22042

Would you try the following:

if [[ -t 0 ]]; then
    # This line is executed when input from the terminal.
    echo "Input a numeric value and enter then continue. Enter a blank line when done."
fi

while read -r n; do
    [[ -z $n ]] && break    # exits the loop if the input is empty
    ary+=("$n")
done

sorted=($(sort -n < <(printf "%s\n" "${ary[@]}")))
printf "%s\n" "${sorted[@]}"
  • It accepts both user's input from the terminal and redirection from a file.
  • It expects the input to be a list of values separated by newlines.
  • When typing on the terminal, a user can complete the input by entering a blank line or pressing Ctrl+D.
  • The array ary holds the values in the input order.
  • The array sorted holds the sorted result.
  • The script does not check the validity of the input values. It may be better to examine if the input is a valid numeric value depending on the application.

Hope this helps.

Upvotes: 1

sebastian
sebastian

Reputation: 1688

Where does the input come from? Someone entering numbers, or a file, another process?

Either way, you seem to expect a finite number of inputs which then need sorting. Just pipe your inputs into sort -n (-n is for numeric sort). No need to use an intermediate array.

# Print some numbers on the console, pipe into sort.
cat <<-EOF | sort -n
1
3
2
EOF

If your inputs are coming from a file:

# Create FILE holding unsorted numbers.
$ cat <<-EOF > FILE 
1
3
2
EOF

# Sort contents of FILE.
$ cat FILE | sort -n
1
2
3

If you could be more specific, it would be easier to help.

Upvotes: 1

Related Questions