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

9,282

Solution 1

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.

Solution 2

If the files are all in the same directory, you have some other options in addition to jasonwryan's answer.

Using a glob:

files=(file[0-9].txt)

Only matching the example files in the question:

files=(file[1-3].txt)

If you have bash version 4 or higher, you can even glob recursively:

shopt -s globstar
files=(**/file[0-9].txt)

Using brace expansion to restrict your array to only your example files:

files=(file{1..3}.txt)

Unlike the other two examples, this will populate the array with the filenames, even if they do not exist. For this reason, the brace expansion may not be desirable.

Share:
9,282

Related videos on Youtube

N. F.
Author by

N. F.

1/0

Updated on September 18, 2022

Comments

  • N. F.
    N. F. almost 2 years

    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.

    • Admin
      Admin over 11 years
      If you know the names what do you mean by 'find'? Do you want to create an array with these three strings in it?
    • Admin
      Admin over 11 years
      A=(file*); echo ${A[@]}
    • Admin
      Admin over 11 years
      I have edited my explanation above.
  • jordanm
    jordanm over 11 years
    Find is not needed with your example, but it still gets the job done of demonstrating a safe way to use find to populate an array +1. One note is that not all version of find support -print0.
  • jasonwryan
    jasonwryan over 11 years
    You are right. Given the lack of detail around the actual problem, I thought it better to direct the OP to the Wooledge Wiki for a more thorough explanation.
  • jordanm
    jordanm over 11 years
    As a regular on the #bash IRC channel whose members maintain that wiki, I agree.