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 ?
You may use a single awk
:
rpm -qa |
awk -F- '/^kafka_/ && split($2, a, /\./) >= 1 {print a[1] "." a[2]}'
1.0
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
Does this sed
work?
rpm -qa | grep '^kafka_' | sed 's/[a-z0-9_]*-\(...\).*/\1/'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With