Home > Mobile >  extract nth number in a string using bash commands
extract nth number in a string using bash commands

Time:01-18

running the following command I get 0271, is there a way to get 0, 27, and 1 separately?

echo '!    ibrav = 0, nat = 27, ntyp = 1' | sed -r 's/[^1-9]*//g'

CodePudding user response:

Use grep instead of sed. The -o option prints just the matching parts, and each match is on a separate line.

echo '!    ibrav = 0, nat = 27, ntyp = 1' | grep -E -o '[0-9] '

Output:

0
27
1

CodePudding user response:

I found this approach to work in both bash and make environments. assuming;

VAR='!    ibrav = 0, nat = 27, ntyp = 1'

bash:

echo $(VAR) | grep -Po '(nat = \d )')

make:

$(eval NUM := $(shell echo $(VAR) | grep -Po '(nat = \d )'))
  •  Tags:  
  • Related