linux: how to capture the number/s from string

0

I use the following syntax in order to capture only the number from machine hostname

echo machineLinux05 | sed s'/\./ /g' | awk '{print $1}' | sed 's/[^0-9]//g'

05

But this way is not so elegant. Is there another short alternative to capture the number from the string?

enodmilvado

Posted 2017-12-31T07:11:34.600

Reputation: 173

1What is the purpose of sed s'/\./ /g' | awk '{print $1}'? In your example, neither of these commands does anything. – John1024 – 2017-12-31T07:28:12.120

the purpose is in case hostname have also the domain name as machineLinux05.FG.com – enodmilvado – 2017-12-31T08:22:36.970

2tr -cd '[0-9]' <<< "machineLinux05" – Cyrus – 2017-12-31T10:38:33.053

1echo machineLinux05.FG,com | grep -o '[0-9]\+' also works. – Paulo – 2017-12-31T13:36:41.527

Answers

1

You could just get rid of the first sed and awk, they're pointless:

$ echo machineLinux05 | sed 's/[^0-9]//g'

Mureinik

Posted 2017-12-31T07:11:34.600

Reputation: 3 521

in case we have also the domain as machineLinux05.FG,com , then can you please update the answer – enodmilvado – 2017-12-31T08:21:49.390

1@enodmilvado This still prints 05 even with a fully qualified machine name – Mureinik – 2017-12-31T08:30:22.633

0

Try the following one-liner:

echo machineLinux05.FG.com | perl -pe 's/\..*$//;s/[^0-9\n]+//g'

AnFi

Posted 2017-12-31T07:11:34.600

Reputation: 771

in case we have also the domain as machineLinux05.FG,com , then can you please update the answer – enodmilvado – 2017-12-31T08:21:45.083

s/\..*$// removes first dot and all chars after it. – AnFi – 2017-12-31T16:10:27.320