Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Extract first number of a three digit version

Tags:

sed

awk

I would like to extract number 10 from 10.3.0 for Makefile to add specific CFLAGS
Below code is printing only 1030

echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0"|sed -r 's/.* ([0-9])/\1/g' | sed -r 's/\.//g'
1030

How to get the 10

like image 703
Dickens A S Avatar asked Jul 18 '21 05:07

Dickens A S


Video Answer


3 Answers

A simple awk:

echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0" | awk '{print int($NF)}'
10

Or if you must use sed only then:

echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0" |
sed -E 's/.* ([0-9]+).*/\1/'

10
like image 115
anubhava Avatar answered Oct 08 '22 22:10

anubhava


Just a tiny tweak to your own solution would do:

echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0"|sed -r 's/.* ([0-9])/\1/g' | sed -r 's/\..*//g'
10

Actually the second sed is not needed here:

echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0"|sed -r 's/.* ([0-9]+).*/\1/g'
10

What happened is that you replaced things before 10 but not after it, which can be easily fixed.

like image 3
Tiw Avatar answered Oct 09 '22 00:10

Tiw


This solution using the awk functions match() and substr():

echo 'gcc.exe (Rev5, Built by MSYS2 project) 10.3.0' | awk 'match($0, /[[:digit:]]+\./) {print substr($0,RSTART,RLENGTH-1)}'
10
like image 2
Carlos Pascual Avatar answered Oct 08 '22 22:10

Carlos Pascual