Home > Software engineering >  Want to extract a number included in a path so how to extract 24?
Want to extract a number included in a path so how to extract 24?

Time:01-29

just wanted to extract a number included in a path path is stored in catalina_home string as "/opt/hpws24/tomcat" so How to extract 24

I tried

catahome='/opt/hpws24/tomcat'
version=$(echo "$catalina_home" | grep -o -E '[0-9] ')
echo $version

which is giving me 24 but still i want only the number which attached to hpws because my code is giving all the numbers with space separated in case opt or tomcat is having a number sttached in future, So i want only a number attached 2 hpws. please guide me

CodePudding user response:

Problem in OP's attempt is, using grep to simply find Digits in whole variable value which may lead to get false positive results too.

With your shown samples/attempts, please try following awk program.

catahome="/opt/hpws24/tomcat"
echo "$catahome" | awk -F'/' '{sub(/[^0-9] /,"",$3);print $3}'

Explanation: Printing value of string with echo command and sending its output as a standard input to awk command. In awk program, using -F option to set field separator as / for all the lines. In main program using sub function of awk to substitute everything apart from digits with NULL and printing 3rd column then.

CodePudding user response:

You did a small mistake

version=$(echo "$catalina_home" | grep -o -E '[0-9] ')

should be

version=$(echo "$catahome" | grep -o -E '[0-9] ')

Here the output that i got

nabil@LAPTOP~$ catahome='/opt/hpws24/tomcat'
nabil@LAPTOP:~$ version=$(echo "$catahome" | grep -o -E '[0-9] ')
nabil@LAPTOP:~$ echo $version
24

  •  Tags:  
  • Related