Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash + how to capture the version from rpm

this is the way when I try to get the Kafka version

rpm -qa | grep "^kafka_"
kafka_2_6_5_0_292-1.0.0.2.6.5.0-292.noarch

Kafka version is 1.0 , so I did the following in order to cut the Kafka version

 rpm -qa | grep "^kafka_" | sed s'/-/ /g' | awk '{print $2}' | cut -c 1-3
 1.0              <-----   results 

above cli seems to be not so elegant and long syntax

can we do it better , maybe with Perl or Python one liner command ?

like image 949
jessica Avatar asked Sep 01 '21 07:09

jessica


4 Answers

You may use a single awk:

rpm -qa |
awk -F- '/^kafka_/ && split($2, a, /\./) >= 1 {print a[1] "." a[2]}'

1.0
like image 86
anubhava Avatar answered Oct 18 '22 19:10

anubhava


Refactoring your code

rpm -qa | grep "^kafka_" | sed s'/-/ /g' | awk '{print $2}' | cut -c 1-3

1st step: use AWK's FS (Field Seperator) instead preprocessing in sed

rpm -qa | grep "^kafka_" | awk 'BEGIN{FS="-"}{print $2}' | cut -c 1-3

2nd step: register {print $2} action to lines matching description rather than filtering it with grep

rpm -qa | awk 'BEGIN{FS="-"}/^kafka_/{print $2}' | cut -c 1-3

3rd step: use AWK's substr function in place of cut -c

rpm -qa | awk 'BEGIN{FS="-"}/^kafka_/{print substr($2,1,3)}'

Disclaimer: my answer assumes you want behavior exactly like your original code, even if possibly unexpected i.e. it does get first 3 characters of version parts, regardless of how many digits are in 2nd part so for example for 1.15.0.2.6.5.0-292 it does yield 1.1

like image 4
Daweo Avatar answered Oct 18 '22 19:10

Daweo


Does this sed work?

rpm -qa | grep '^kafka_' | sed 's/[a-z0-9_]*-\(...\).*/\1/'
like image 3
HatLess Avatar answered Oct 18 '22 19:10

HatLess


if k=$(rpm -qa | grep "^kafka_")
then
  if [[ ${k#*-} =~ ^[0-9]+[.][0-9]+ ]]
  then
    k_version=$BASH_REMATCH
  else
    echo "can not determine kafka version from '$k'"
  fi
else
  echo "No kafka in rpm"
fi

The idea here is to remove everything from the version string up to the dash and then use a regexp to get the version part.

like image 3
user1934428 Avatar answered Oct 18 '22 19:10

user1934428