0

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
8
  • 1
    What do you mean sorting it? Can you show an actual example and let us know what you are trying? Commented Mar 31, 2017 at 7:21
  • updated the post. Currently my array consist of: test_file0.txt, test_file12.txt, test_file11.txt, test_file10.txt and the output I need is: test_file0.txt, test_file10.txt, test_file11.txt, test_file12.txt Commented Mar 31, 2017 at 7:26
  • 1
    When I created some sample files as touch test_file0.txt test_file12.txt test_file11.txt test_file10.txt and echo'd manually as for file in test_file*.txt; do echo "$file"; done, it is in sorted order only Commented Mar 31, 2017 at 7:36
  • @Engah: The logic is pathname expansion in bash to list files always appears in sorted order Commented Mar 31, 2017 at 7:39
  • he probably mean sorted numerically... 1,2,10 and not 1,10,2 Commented Mar 31, 2017 at 7:42

1 Answer 1

1

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[@]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.