Extract substring in Bash

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

    Here's how i'd do it:

    FN=someletters_12345_moreleters.ext
    [[ ${FN} =~ _([[:digit:]]{5})_ ]] && NUM=${BASH_REMATCH[1]}
    

    Explanation:

    Bash-specific:

    • [[ ]] indicates a conditional expression
    • =~ indicates the condition is a regular expression
    • && chains the commands if the prior command was successful

    Regular Expressions (RE): _([[:digit:]]{5})_

    • _ are literals to demarcate/anchor matching boundaries for the string being matched
    • () create a capture group
    • [[:digit:]] is a character class, i think it speaks for itself
    • {5} means exactly five of the prior character, class (as in this example), or group must match

    In english, you can think of it behaving like this: the FN string is iterated character by character until we see an _ at which point the capture group is opened and we attempt to match five digits. If that matching is successful to this point, the capture group saves the five digits traversed. If the next character is an _, the condition is successful, the capture group is made available in BASH_REMATCH, and the next NUM= statement can execute. If any part of the matching fails, saved details are disposed of and character by character processing continues after the _. e.g. if FN where _1 _12 _123 _1234 _12345_, there would be four false starts before it found a match.

提交回复
热议问题