开发者

From the bash command shell, parsing numbers from a line

I have a log line that I am pulling from bash like:

There are 5 apples and 7 oranges

And I want to get the 5 and 7 into bash variables and am having problems doing so.

awk '{ print $3, $6 }' won't work due to the f开发者_如何学运维act that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.

Thanks in advance


and to get the fruits:

echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+'


A bash-only method, tested with bash v4:

str=" There are 5 apples, 12 bananas and 7 oranges"

i=0
while [[ "$str" =~ ([0-9]+)" "([a-z]+)(.*) ]] ; do
    num[$i]=${BASH_REMATCH[1]}
    type[$i]=${BASH_REMATCH[2]}
    str=${BASH_REMATCH[3]}
    (( i++ ))
done

for (( i=0; i<${#num[@]}; i++ )); do
    printf "%4d\t%s\t%s\n" $i ${num[$i]} ${type[$i]}
done

outputs

   0    5       apples
   1    12      bananas
   2    7       oranges


Grep will do this:

echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+'


Slightly more compact version:

echo 'There are 5 apples and 7 oranges' | egrep -o '[0-9]+ \w+'

Note however that \w is synonymous with [:alnum:], and will thus match "appl3s" as well, for example.


Well, shell is a strange language, and you can do nice things. For example:

a="there are 7 apples"
for i in $a; do
  case $i in
    [0-9]*)
      value=$i
      expectname=1
    ;;
    *)
      test -n "$expectname" && name=$i
      expectname=
    ;;
  esac
done

echo $value
echo $name

If you have more than one occurrence, you can fill an array, or a bash map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜