How to get a substring after the last underscore (_) in unix shell script

后端 未结 3 1099
醉话见心
醉话见心 2021-01-19 18:00

I have a String like this

this_is_test_string1_22
this_is_also_test_string12_6

I wanted to split and extracts string around the last unders

3条回答
  •  梦谈多话
    2021-01-19 18:18

    You can do

    s='this_is_test_string1_22'
    

    In BASH:

    echo "${s##*_}"
    22
    

    OR using sed:

    sed 's/^.*_\([^_]*\)$/\1/' <<< 'this_is_test_string1_22'
    22
    

    EDIT for sh:

    echo "$s" | sed 's/^.*_\([^_]*\)$/\1/'
    

提交回复
热议问题