-1

I'm trying to read numbers from .txt file and than store it into array so I can sort them using bubble sort.

I was trying something like that:

input=$1
readIt=`cat $1`
array=${#readIt[*]}

When I was trying to display it using echo it is displaying good, but when I'm trying to sort it, then it doesn't work.

Any help, please?

EDIT: I checked other topics, but I want to solve this problem using "cat" to understand it in easier way as beginner.

HC1122
  • 404
  • 1
  • 6
  • 19

1 Answers1

2

Use readarray (bash 4+)

readarray -t array < "$1"

or a loop (prior to bash 4):

while IFS= read -r line; do
  array+=("$line")
done < "$1"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • It's not doable using cat function? Since I'm fresh into bash I was trying to use some simple methods. – HC1122 Oct 21 '16 at 15:12
  • 1
    If your file consists of nothing but numbers, you can get away with `array=( $(cat "$1") )`, but that approach assumes that line breaks are no more significant than other whitespace that may appear on a line (that is, you aren't getting one line per element in your array) and that there are no characters that subject you to pattern expansion (like `*` or `?`) in the file. – chepner Oct 21 '16 at 15:14
  • `cat` is not a function; it is a entirely separate program from `bash`. – chepner Oct 21 '16 at 15:14
  • But how can I than bubble sort it? using array[i] and array[j]? Is possible? – HC1122 Oct 21 '16 at 15:22
  • Yes, but that's en entirely separate question. – chepner Oct 21 '16 at 15:23
  • Hm by using that your suggestion I got an error about "too much arguments" when comparing readIt[i] -gt readIt[j] – HC1122 Oct 21 '16 at 15:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126345/discussion-between-hc1122-and-chepner). – HC1122 Oct 21 '16 at 15:27