Engah
Engah

Reputation: 35

Ordering array of strings in bash scripting

I am fairly new to bash scripting. I have a list of files in my directory and I'd like to store them into an array and then sort them inside the array. I've stored the list of files into my array; however, I'm unable to order them.

  for file in test_file*.txt;
  do
    TEST_FILE="${file##*/}"
    arrayname[index]=$TEST_FILE
    index=$(expr $index + 1)
  done

That stores all the files starting with test_file and ending with .txt into my array. The part that I find tricky is sorting it. I've done a bit of digging around, but I could not find the solution.

Also if I was so run compile a python code later, would I do a loop and call

python3 test.py "$arrayname[n]"

and increment n?

My current directory has these files and it is stored in the array "arrayname[]" in the form:

 test_file0.txt, test_file12.txt, test_file11.txt, test_file10.txt, 

I am trying to sort it and store it into another array, so the new array has the following order:

 test_file0.txt, test_file10.txt, test_file11.txt, test_file12.txt

Upvotes: 0

Views: 88

Answers (1)

clt60
clt60

Reputation: 63902

If your sort knows the -V (GNU sort):

readarray -t files < <(printf "%s\n" test_file* | sort -V)
printf "%s\n" "${files[@]}"

#bash 4.4+
readarray -t -d '' files1 < <(find . -maxdepth 1 -name test_file\* -print0 | sort -zV)
printf "%s\n" "${files1[@]}"

Upvotes: 1

Related Questions