Extract substring in Bash

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

    Following the requirements

    I have a filename with x number of characters then a five digit sequence surrounded by a single underscore on either side then another set of x number of characters. I want to take the 5 digit number and put that into a variable.

    I found some grep ways that may be useful:

    $ echo "someletters_12345_moreleters.ext" | grep -Eo "[[:digit:]]+" 
    12345
    

    or better

    $ echo "someletters_12345_moreleters.ext" | grep -Eo "[[:digit:]]{5}" 
    12345
    

    And then with -Po syntax:

    $ echo "someletters_12345_moreleters.ext" | grep -Po '(?<=_)\d+' 
    12345
    

    Or if you want to make it fit exactly 5 characters:

    $ echo "someletters_12345_moreleters.ext" | grep -Po '(?<=_)\d{5}' 
    12345
    

    Finally, to make it be stored in a variable it is just need to use the var=$(command) syntax.

提交回复
热议问题