0

I have a string like that:

rthbp-0.0.3-sources.jar

And i want to get a new string called in someway (like string2) with the original string with just the version , so - '0.0.3' now rthbp- at the start will remain constant but after version "-" (-sources.jar) may change.

is that possible in bash, just to extract the version info ?

I am doing this - echo ${f:6} but only gives me 0.0.3-sources.jar

Scooby
  • 3,371
  • 8
  • 44
  • 84

6 Answers6

3

If you're using bash, you can extract an arbitrary substring by specifying both offset and length:

$ filename=rthbp-0.0.3-sources.jar
$ echo "${filename:6:5}"
#=> 0.0.3

But using exact character offsets like that is fragile. You might want to use something like this:

$ IFS=- read pre version post <<<"$filename"
$ echo "$version"
#=> 0.0.3

Or, somewhat more clunkily:

$ ltrim=${filename%%-*}-
$ rest=${filename#$ltrim}
$ version=${rest%%-*}

Or as others mentioned you could call out to cut or awk to do the splitting for you..

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • The clunky code can be simplified a bit:`version_and_suffix=${filename#rthbp-}; version=${version_and_suffix%%-*}` – pjh Sep 30 '15 at 19:26
  • I was trying not to assume that we know the first part of the filename that exactly, but sure. – Mark Reed Sep 30 '15 at 20:50
3

No one has mentioned regular expression matching yet, so I will.

[[ $string1 =~ rthbp-(.*)-sources.jar ]]
version=${BASH_REMATCH[1]}

(You may want a slightly more general regular expression; this just demonstrates how to match against a regular expression containing a capture group and how to extract the captured value.)

chepner
  • 497,756
  • 71
  • 530
  • 681
2

You can use read built-in:

s='rthbp-0.0.3-sources.jar'
IFS=- read a ver _ <<< "$s" && echo "$ver"
0.0.3
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

I would recommend just using cut for this. Define the delimiter as dashes and keep field two:

$ echo "rthbp-0.0.3-sources.jar" | cut -d'-' -f 2
0.0.3

If you want to use pure bash, you can use parameter expansion, but it isn't as clean. Assuming the version always starts in the same place and is the same length, you can use:

$ str="rthbp-0.0.3-sources.jar"

$ echo "${str:6:5}"
0.0.3
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
1

Another variant of regex match:

$ echo "rthbp-0.0.3-sources.jar"|grep -e '([[:digit:]]+\.)+[[:digit:]]+' -oP
0.0.3
James Jithin
  • 10,183
  • 5
  • 36
  • 51
0
echo "rthbp-0.0.3-sources.jar" | awk -F- '$2=="0.0.3"{print $2}'
0.0.3


echo "rthbp-0.0.3-sources.jar" | awk -F- '{print $2}'
0.0.3
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8