如何在shell中提取数字并分配到变量中

时间:2018-03-15 18:42:54

标签: linux bash shell awk grep

echo DEN_ML2.3_R02.zip | grep -o '[0-9]\+'

Output: 

2
3  
02

我想从2.3 grep 02DEN_ML2.3_R02.zip并分配给变量

1 个答案:

答案 0 :(得分:1)

$ echo DEN_ML2.3_R02.zip | grep -Eo '\-?[0-9]+(\.[0-9]+)?'
                                              _________ _
                                                ^       ^
                                             group    quantifier

量词?表示该群组可选

输出:

2.3
02

分配给变量要求:

$ read a1 a2 < <(echo $(grep -Eo '\-?[0-9]+(\.[0-9]+)?' <<< "DEN_ML2.3_R02.zip"))

$ read a1 a2 < <(
    grep -Eo '\-[0-9]+(\.[0-9]+)?' <<< "DEN_ML2.3_R02.zip" |
    tr '\n' ' '
)

结果:

$ echo $a1
2.3
$ echo $a2
02