SegFault
SegFault

Reputation: 2190

Extract one number from string in bash

I have this string:

1024.00 MB transferred (912.48 MB/sec)

and I need to get only the number 912.48 and transform it in 912,48 with a bash script. I tried to do sed 's/[^0-9.]*//g' but in this way i get 1024.00 912.18. How can I do it?

Upvotes: 1

Views: 118

Answers (8)

Charles Duffy
Charles Duffy

Reputation: 295281

So far, every answer here is using external tools (sed, awk, grep, tr, etc) rather than sticking to native bash functionality. Since spinning up external processes has a significant constant-time performance impact, it's generally undesirable when only processing a single line of content (for long streams of content, an external tool will often be more efficient).

This one uses built-ins only:

# one-time setup: set the regex
re='[(]([0-9.]+) MB/sec[)]'
string='1024.00 MB transferred (912.48 MB/sec)'

if [[ $string =~ $re ]]; then  # run enclosed code only if regex matches
  val=${BASH_REMATCH[1]}       # refer to first (and only) match group
  val_with_comma=${val//./,}   # replace "." with "," in that group
  echo "${val_with_comma}"     # ...and emit our output
fi

...yielding:

912,48

Upvotes: 2

webb
webb

Reputation: 4340

wow, so many answers :)

here's mine, should be pretty fast:

grep -o '([^ ]\+' | tail -c+2 | tr '.' ','

Upvotes: 0

Zlemini
Zlemini

Reputation: 4963

A combination of awk and sed:

str='1024.00 MB transferred (912.48 MB/sec)'
echo "$str" | awk '{print $4}' | sed 's/(//;s/\./,/'

912,48

Or entirely with awk:

echo "$str" | awk '{sub("[(]","");sub("[.]",",");print $4}'

Upvotes: 1

anubhava
anubhava

Reputation: 784898

Here is an awk to get the job done:

s='1024.00 MB transferred (912.48 MB/sec)'
awk -F '[() ]+' '{sub(/\./, ",", $4); print $4}' <<< "$s"

912,48

Upvotes: 0

twalberg
twalberg

Reputation: 62369

Another of the near-infinite possibilities:

read x y < <(tr -dc '[0-9. ]' <<< "1024.00 MB transferred (912.48 MB/sec)")
echo ${y}

or

grep -oP '(?<=\()[\d.]+' <<< "1024.00 MB transferred (912.48 MB/sec)"

Upvotes: 0

A R
A R

Reputation: 2803

echo "1024.00 MB transferred (912.48 MB/sec)" | cut -d " " -f4 | tr "." "," | tr -d "("

Upvotes: 0

codeforester
codeforester

Reputation: 42999

echo "1024.00 MB transferred (912.48 MB/sec)" | cut -f2 -d'(' | cut -f1 -d' ' | sed 's/\./,/'

Upvotes: 1

karakfa
karakfa

Reputation: 67467

this should work

$ sed -r 's/.*\(([0-9.]+).*/\1/;s/\./,/'

Upvotes: 1

Related Questions