Reputation: 4054
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
Upvotes: 5
Views: 571
Reputation: 133640
With shown samples, you could try following. Simple explanation would be, make .
and )
as field separators and print 3rd field if NF is greater than 2 for that line, to get required output as per shown samples.
echo "gcc.exe (Rev5, Built by MSYS2 project) 10" |
awk -F'\\.|\\) ' 'NF>=2{print $3}'
Upvotes: 2
Reputation: 163467
You code using sed gives 1030 as a result because s/.* ([0-9])/\1/g
will leave 10.3.0 and then s/\.//g
will remove all the dots leaving 1030.
You could match the format ^[0-9]+\.[0-9]+\.[0-9]+$
of the last field $NF
, and if it matches split on a dot and print the first part.
echo "gcc.exe (Rev5, Built by MSYS2 project) 10.3.0" | awk 'match($NF, /^[0-9]+\.[0-9]+\.[0-9]+$/) {
split($NF,a,"."); print a[1]
}
'
Output
10
Upvotes: 2
Reputation: 1126
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
Upvotes: 2
Reputation: 5252
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.
Upvotes: 3
Reputation: 785611
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
Upvotes: 6