我试图从存储在变量中的数据中仅获取百分比部分的值,我也想仅获取输出中存在的第一个百分比值。
<map id="09EhL_map" name="09EhL_map">
<area shape="poly" coords="374,274,374,274,376,274,376,274,376,274,376,274" title="5-April-2019: 0.0% of runs for TT1 were successful" alt="" nohref="nohref"/>
<area shape="poly" coords="368,274,368,274,371,274,374,274,374,274,374,274" title="4-April-2019: 20.0% of runs for TT2 were successful" alt="" nohref="nohref"/>
我做了什么
var1="<map id="09EhL_map" name="09EhL_map">
<area shape="poly" coords="374,274,374,274,376,274,376,274,376,274,376,274" title="5-April-2019: 0.0% of runs for HIP-HCTP-HIP3 were successful" alt="" nohref="nohref"/>
<area shape="poly" coords="368,274,368,274,371,274,374,274,374,274,374,274" title="4-April-2019: 0.0% of runs for HIP-HCTP-HIP3 were successful" alt="" nohref="nohref"/>"
var2=$(echo var1 | grep "%")
这不会返回任何内容。
答案1
您可以使用:
var2=$(echo $var1 | grep -o [0-9][0-9]*\.[0-9][0-9]*%)
这里将匹配末尾grep -o [0-9][0-9]*\.[0-9][0-9]*%
有符号的浮点数。%
在你的情况下它会打印
0.0%
20.0%
如果您只想获得第一个匹配项,请使用:
var2=$(echo $var1 | grep -o [0-9][0-9]*\.[0-9][0-9]*% | head -n1)