Extract substring in Bash

前端 未结 22 2060
别那么骄傲
别那么骄傲 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:29

    If x is constant, the following parameter expansion performs substring extraction:

    b=${a:12:5}
    

    where 12 is the offset (zero-based) and 5 is the length

    If the underscores around the digits are the only ones in the input, you can strip off the prefix and suffix (respectively) in two steps:

    tmp=${a#*_}   # remove prefix ending in "_"
    b=${tmp%_*}   # remove suffix starting with "_"
    

    If there are other underscores, it's probably feasible anyway, albeit more tricky. If anyone knows how to perform both expansions in a single expression, I'd like to know too.

    Both solutions presented are pure bash, with no process spawning involved, hence very fast.

提交回复
热议问题