Reputation: 1074
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
Reputation: 7801
You need to use an array.
#!/usr/bin/env bash
shopt -s extglob
versions=(/home/test/file*)
printf '%s\n' "${versions[@]##*+([[:alpha:]])}"
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
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