简体   繁体   English

bash脚本中的字符串排序数组

[英]Ordering array of strings in bash scripting

I am fairly new to bash scripting. 我对bash脚本非常陌生。 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. 它将所有以test_file开头并以.txt结尾的文件存储到我的数组中。 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 另外,如果我这么晚才编译python代码,我会做一个循环并调用

python3 test.py "$arrayname[n]"

and increment n? 并增加n?

My current directory has these files and it is stored in the array "arrayname[]" in the form: 我当前的目录中包含以下文件,并以以下形式存储在数组“ arrayname []”中:

 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

If your sort knows the -V (GNU sort): 如果您的sort知道-V (GNU排序):

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[@]}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM