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 ! ;)

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.

  • 1
    Instead of seq ..., use ${!files[@]} - that lists out the indexes. – muru Feb 26 '15 at 17:57
  • @muru: I have not seen that one before. Good to know, thanks. – Thor Feb 26 '15 at 18:00
  • With proper quoting, spaces and newlines shouldn't be a problem for arrays made from globbing. – muru Feb 26 '15 at 18:06
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
  • why not using files=( "/home/user/Documents/*_suffix.txt" ) alone? – αғsнιη Feb 26 '15 at 17:58
  • @KasiyA Let's say the path and suffix are arguments to the script or something like that. (Also, quote over * will prevent globbing.) – muru Feb 26 '15 at 17:59
  • Then in that case files=( "$1"/*"_$2" ). The $1 for path and $2 for suffix – αғsнιη Feb 26 '15 at 18:01
  • @KasiyA * outside the quotes! – muru Feb 26 '15 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.