3

i'm making a little shell script and i want to stock all files with same suffix in a table.

i want something like that :

path=/home/user/Documents
suffix="_suffix.txt"

and then a function that create a table name files and fill it with file in $path with $suffix suffix. result :

echo files[0]

-> /home/user/Documents/project_suffix.txt

echo files[1]

-> /home/user/Documents/html_suffix.txt

echo files[2]

-> /home/user/Documents/jokes_suffix.txt. etc...

I don't want to have in my list other files like "budget.txt"

Thanks for your answers ! ;)

muru
  • 207,228

2 Answers2

4

This is fairly straightforward with recent versions of bash by using globbing and arrays, which is what I assume you mean by tables.

First create some test files:

path=/some/where
touch $path/{a,b,c}_suffix.txt

Here is an example that puts all files ending in _suffix.txt into the files array:

files=("$path"/*_suffix.txt)

To iterate over them you can do something like this:

for file in "${files[@]}"; do
  echo "$file"
done

Or:

for i in ${!files[@]}; do
  echo "${files[i]}"
done

Note, filenames with spaces and newlines in them will cause problems with this approach. In that case you are better of with a find and -print0 loop, see this answer for an example and this write-up for details.

Edit

As noted by muru, the whitespace problem may not be as problematic as it used to be, YMMV.

Thor
  • 3,678
2

What you call a table is usually called an array or a map. In bash, to create such an array:

path="/home/user/Documents"
suffix="_suffix.txt"
files=( "$path"/*"$suffix" )

The * is a wildcard, which is expanded by the shell to all matching filenames (that have $path before it and $suffix after). The brackets (()) convert the expanded filenames into an array.

Then you can access each element (indexed from 0, instead of 1) using "${files[0]}", "${files[1]}", etc.

For example:

$ path=/tmp
$ suffix=_amd64.deb
$ files=( "$path"/*"$suffix" )
$ echo "${files[1]}" "${files[0]}" 
/tmp/vim-athena_7.4.640-1~ppa1~t_amd64.deb /tmp/vim_7.4.640-1~ppa1~t_amd64.deb
muru
  • 207,228