Reputation: 2190
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
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
Reputation: 4340
wow, so many answers :)
here's mine, should be pretty fast:
grep -o '([^ ]\+' | tail -c+2 | tr '.' ','
Upvotes: 0
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
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
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
Reputation: 2803
echo "1024.00 MB transferred (912.48 MB/sec)" | cut -d " " -f4 | tr "." "," | tr -d "("
Upvotes: 0
Reputation: 42999
echo "1024.00 MB transferred (912.48 MB/sec)" | cut -f2 -d'(' | cut -f1 -d' ' | sed 's/\./,/'
Upvotes: 1