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 ?

Answer

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