0

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'
Amir
  • 3
  • 1

2 Answers2

2

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • grep still doesn't let me access the numbers separately to assign them to different variables – Amir Jan 18 '22 at 02:34
  • It puts them each on a different line of the output. – Barmar Jan 18 '22 at 02:34
  • yes, how do I assign each to different variables? – Amir Jan 18 '22 at 02:36
  • You can put them in an array: `arrayvar=($(echo '! ibrav = 0, nat = 27, ntyp = 1' | grep -E -o '[0-9]+'))` – Barmar Jan 18 '22 at 02:38
  • why it doesn't work in a make file like this: `$(eval NUM := ($(shell echo $(VAR) | grep -E -o '[0-9]+')))` – Amir Jan 18 '22 at 02:51
  • `make` doesn't have arrays. – Barmar Jan 18 '22 at 02:53
  • You're trying to mix bash and make syntax. – Barmar Jan 18 '22 at 02:54
  • The question said nothing about `make`, it was about `bash`. – Barmar Jan 18 '22 at 02:54
  • yes, I want to use it in a make environment what would be a good approach for that? – Amir Jan 18 '22 at 02:55
  • You might get some ideas here: https://stackoverflow.com/questions/49983726/variables-in-makefiles-how-to-use-arrays – Barmar Jan 18 '22 at 02:56
  • @Amir: (1) If you want the result in three separate variables instead of an array, use `grep -o` together with the `read` command. (2) If you have new requirements which are not present in your original question, please ask a new question and don't discuss new problems in comments. – user1934428 Jan 18 '22 at 07:49
0

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+)'))
Amir
  • 3
  • 1