radicaled
radicaled

Reputation: 2669

Get version from file name

I'm creating a script that list all the jboss versions. But I was caught in a problem.
Jboss usually has different names for the version.
jboss-4.0.0.tar.gz
jboss-4.0.4.GA.tar.gz

I managed to obtain the version (for example 4.0.0 or 4.0.4). But I need to obtain all the version 4.0.4.GA

ls -1 | grep jboss |sed -r 's/^.*-([0-9.]+)\..*/\1/'

Thanks

Upvotes: 0

Views: 1231

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185126

Don't parse ls output.

ls is a tool for interactively looking at file information. Its output is formatted for humans and will cause bugs in scripts. Use globs (like I do here) or find instead. Understand why: http://mywiki.wooledge.org/ParsingLs

$ ls -1
jboss-4.0.0.tar.gz
jboss-4.0.4.GA.tar.gz
foobar

Using :

 $ printf -- '%s\n' * | grep -oP 'jboss-\K.*(?=\.tar\.gz)'

Or using :

$ printf -- '%s\n' * | awk -F'jboss-|.tar.gz' '/jboss/{print $2}'

Or using :

printf -- '%s\n' * | perl -lne '/jboss-(.*?)\.tar\.gz/ && print $1'

Outputs

4.0.0
4.0.4.GA

Upvotes: 3

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45576

$ cat test.sh
#!/bin/bash

for file in jboss-*.tar.gz; do
        [ -f "${file}" ] || continue
        version="${file#*-}"
        version="${version%.tar.gz}"
        echo "${version}"
done

Example:

$ find
.
./test.sh
./jboss-4.0.0.tar.gz
./jboss-4.0.4.GA.tar.gz

$ ./test.sh
4.0.0
4.0.4.GA

Upvotes: 0

Related Questions