ToX 82
ToX 82

Reputation: 1074

List matching files into an array

I am trying to make a script that lists the available versions of a file, like this:

/home/test/file1.0
/home/test/file1.1
/home/test/file2.0
/home/test/file2.1
...
/home/test/file2.14

What I'd need is an array containing all of the values: 1.0, 1.1, 2.0, 2.1, ..., 2.14. Now I came up to this:

VERSIONS=$(ls /home/test/file* | egrep '[0-9]+\.[0-9]+' | cut -c 16-);

Which somehow works, but the result is a string like this

1.0 1.1 2.0 2.1 ... 2.14

I'd need an array though. How can I have the result as array of values, instead of a single string?

Upvotes: 1

Views: 385

Answers (2)

Jetchisel
Jetchisel

Reputation: 7801

You need to use an array.

#!/usr/bin/env bash

shopt -s extglob

versions=(/home/test/file*)

printf '%s\n' "${versions[@]##*+([[:alpha:]])}"
  • Needs an extglob bash shell option.

To save to save that output.

array=("${versions[@]##*+([[:alpha:]])}")

Your version can be done with something like

versions=(/home/test/file*)

mapfile -t array < <(printf '%s\n' "${versions[@]}" | egrep '[0-9]+\.[0-9]+' | cut -c 16-)

Now "${array[@]}" has the values that you're interested in.

Upvotes: 2

choroba
choroba

Reputation: 241928

Don't use ls. Use a wildcard to populate the array, then use parameter expansion to remove the prefix from all the elements of the array:

files=( file* )
versions=( "${files[@]#file}" )

Upvotes: 2

Related Questions