Extract substring in Bash

前端 未结 22 2047
别那么骄傲
别那么骄傲 2020-11-22 11:02

Given a filename in the form someletters_12345_moreleters.ext, I want to extract the 5 digits and put them into a variable.

So to emphasize the point, I

22条回答
  •  青春惊慌失措
    2020-11-22 11:16

    Here's a prefix-suffix solution (similar to the solutions given by JB and Darron) that matches the first block of digits and does not depend on the surrounding underscores:

    str='someletters_12345_morele34ters.ext'
    s1="${str#"${str%%[[:digit:]]*}"}"   # strip off non-digit prefix from str
    s2="${s1%%[^[:digit:]]*}"            # strip off non-digit suffix from s1
    echo "$s2"                           # 12345
    

提交回复
热议问题