![awk 或 grep 在 shell 中获取特定字符串](https://linux22.com/image/151338/awk%20%E6%88%96%20grep%20%E5%9C%A8%20shell%20%E4%B8%AD%E8%8E%B7%E5%8F%96%E7%89%B9%E5%AE%9A%E5%AD%97%E7%AC%A6%E4%B8%B2.png)
我试图从存储在变量中的数据中仅获取百分比部分的值,我也想仅获取输出中存在的第一个百分比值。
<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)