Bash:从字符串中提取(百分比)可变长度的数量

时间:2013-01-30 13:22:55

标签: string bash numbers progress-bar

我想使用bash脚本编写一个小进度条。

要生成进度条,我必须从日志文件中提取进度。

此类文件的内容(此处为run.log)如下所示:

  

完成时间2d 15h,完成42.5%,时间步长231856

我现在有兴趣将42.5%的人隔离开来。现在的问题是这个数字的长度是可变的以及数字的位置(例如'完成时间'可能只包含一个数字,如23h或59min)。

我通过

尝试了这个位置
echo "$(tail -1 run.log | awk '{print $6}'| sed -e 's/[%]//g')"

短暂的'完成时间'以及通过%-sign

失败
echo "$(tail -1 run.log | egrep -o '[0-9][0-9].[0-9]%')"

此处仅适用于数字> = 10%。

任何更多变量的数值提取的解决方案?

=============================================== =======

更新:现在是进度条的完整脚本:

#!/bin/bash

# extract % complete from run.log
perc="$(tail -1 run.log | grep -o '[^ ]*%')"

# convert perc to int
pint="${perc/.*}"

# number of # to plot
nums="$(echo "$pint /2" | bc)"

# output
echo -e ""
echo -e "   completed: $perc"
echo -ne "   "
for i in $(seq $nums); do echo -n '#'; done
echo -e ""
echo -e "  |----.----|----.----|----.----|----.----|----.----|"
echo -e "  0%       20%       40%       60%       80%       100%"
echo -e ""
tail -1 run.log
echo -e ""

感谢您的帮助,伙计们!

4 个答案:

答案 0 :(得分:3)

基于您的示例

grep -o '[^ ]*%'

应该给你想要的东西。

答案 1 :(得分:1)

您可以从以下命令中提取%:

tail -n 1 run.log | grep -o -P '[0-9]*(\.[0-9]*)?(?=%)'

说明:

grep options:
-o : Print only matching string.
-P : Use perl style regex

regex parts:
[0-9]* : Match any number, repeated any number of times.
(\.[0-9]*)? : Match decimal point, followed by any number of digits. 
              ? at the end of it => optional. (this is to take care of numbers without fraction part.)
(?=%)  :The regex before this must be followed by a % sign. (search for "positive look-ahead" for more details.)

答案 2 :(得分:0)

您应该能够在文件中第一个comma (,)之后隔离进度。 ie。你想要,%

之间的字符

答案 3 :(得分:0)

有很多方法可以实现您的目标。我希望多次使用 cut ,因为它很容易阅读。

cut -f1 -d'%' | cut -f2 -d',' | cut -f2 -d' '

首先剪切

 Time to finish 2d 15h, 42.5

秒后(注释空格):

 42.5

最后一个只是为了摆脱空间,最后的结果是:

42.5
相关问题