[英]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. 我只需要获取数字
912.48
并使用bash脚本将其转换为912,48
。 I tried to do sed 's/[^0-9.]*//g'
but in this way i get 1024.00 912.18
. 我试图做
sed 's/[^0-9.]*//g'
但是这样我得到了1024.00 912.18
。 How can I do it? 我该怎么做?
So far, every answer here is using external tools ( sed
, awk
, grep
, tr
, etc) rather than sticking to native bash functionality. 到目前为止,这里的每个答案都是使用外部工具(
sed
, awk
, grep
, tr
等),而不是坚持使用本机bash功能。 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
这应该工作
$ sed -r 's/.*\(([0-9.]+).*/\1/;s/\./,/'
echo "1024.00 MB transferred (912.48 MB/sec)" | cut -f2 -d'(' | cut -f1 -d' ' | sed 's/\./,/'
A combination of awk
and sed
: awk
和sed
组合:
str='1024.00 MB transferred (912.48 MB/sec)'
echo "$str" | awk '{print $4}' | sed 's/(//;s/\./,/'
912,48
Or entirely with awk
: 或完全使用
awk
:
echo "$str" | awk '{sub("[(]","");sub("[.]",",");print $4}'
echo "1024.00 MB transferred (912.48 MB/sec)" | cut -d " " -f4 | tr "." "," | tr -d "("
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)"
Here is an awk
to get the job done: 这是完成工作的
awk
:
s='1024.00 MB transferred (912.48 MB/sec)'
awk -F '[() ]+' '{sub(/\./, ",", $4); print $4}' <<< "$s"
912,48
wow, so many answers :) 哇,这么多答案:)
here's mine, should be pretty fast: 这是我的,应该很快:
grep -o '([^ ]\+' | tail -c+2 | tr '.' ','
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.