Bash – How to put the specific files from a directory in an array in bash

bashfilenameswildcards

Suppose I have a directory under which there are 3 files named: file1.txt,file2.txt and file3.txt.

Now how can I fill an array with those file names(I just know that all the files have certain prefix, i.e. file, after file it can be 1,2,3 etc.

Best Answer

From Greg's Wiki: the Bash Guide entry on arrays:

files=()
while read -r -d $'\0'; do
    files+=("$REPLY")
done < <(find *.txt -print0)

There is a detailed explanation of arrays on the page that breaks this construct down element by element; it is well worth reading in full.

Related Question