0

sorry if repeated but i can not find it. I have the following shell string

#!/bin/sh
word_1="/dev/sda5 233371648 242774015 9402368 4,5G 82 Linux swap / Solaris"

I need to extract all the integer numbers from it and save it into array ? Is it possible to have 4,5G inside the same array as the integers. If not I am fine with extracting the integers numbers only.

Inian
  • 80,270
  • 14
  • 142
  • 161
halim
  • 386
  • 4
  • 14
  • Are you using the `POSIX` shell `sh` or bourne again shell `bash` – Inian May 12 '17 at 09:25
  • 1
    Did you try anything – 123 May 12 '17 at 09:28
  • I am using ubuntu 16.4. I think it is POSIX. it has both /bin/sh and /bin/bash. I do not know the difference actually very precise. – halim May 12 '17 at 10:00
  • @halim: Can you share the exact output you need for the above output? do you need the `5` as part of the `/dev/sda5`? – Inian May 12 '17 at 10:34
  • @Inian. It is clear what i need to have. An array that contains all the numbers in the string provided, that is [233371648 242774015 9402368 82] I mentioned also in my question that I am fine with integers. If you can make it as follows [233371648 242774015 9402368 4.5 82] then it is more than fine. – halim May 12 '17 at 11:57

2 Answers2

1

But if you want only the integers but allowing k, M, G, etc, then try:

unset a; let i=0; declare -a a ;  for b in $word_1 ; do [[ $b =~ ^-?[0-9,kMG]+$ ]] && a[i++]=$b ; done ; echo ${a[*]}
Wayne Vosberg
  • 1,023
  • 5
  • 7
  • Thanks for this answer, however I can not understand it fully but it works, I would have preferred to have 4,5G to be in the array as number as well e.g 4.5 and not 4.5G. Many Thanks again! – halim May 12 '17 at 11:51
0

This one works for me:

#!/bin/bash
word="/dev/sda5 233371648 242774015 9402368 4,5G 82 Linux swap / Solaris"
separated=$(echo ${word} | sed -e 's/ /\n/g')
array=$(echo "${separated}" | sed -e '/^[0-9]*$/!d')
echo ${array}
echo "${array}"

The first echo command writes out all the numbers in one line, while the second writes out each number on a different line. Note that some versions of sed do not support the newline character '\n'. On MacOS, for instance, I have to use gsed instead to get the same functionality.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63
  • It perfectly works even though 4.5G is not catched as number in the array but I am fine with the intergers. Thanks! do you know why when i change from #!/bin/bash to #!/bin/sh I get an error and the script doesn't work ? – halim May 12 '17 at 11:54
  • Maybe it's best, if you have a look at this post: http://stackoverflow.com/questions/5725296/difference-between-sh-and-bash – Thomas Kühn May 12 '17 at 18:42