halim
halim

Reputation: 386

Extract numbers from bash string and save the resut into array

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.

Upvotes: 0

Views: 1309

Answers (2)

Wayne Vosberg
Wayne Vosberg

Reputation: 1053

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[*]}

Upvotes: 1

Thomas Kühn
Thomas Kühn

Reputation: 9820

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.

Upvotes: 0

Related Questions