Extract substring in Bash

前端 未结 22 1870
别那么骄傲
别那么骄傲 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
    
    0 讨论(0)
  • 2020-11-22 11:19

    just try to use cut -c startIndx-stopIndx

    0 讨论(0)
  • 2020-11-22 11:19

    Building on jor's answer (which doesn't work for me):

    substring=$(expr "$filename" : '.*_\([^_]*\)_.*')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:21

    Use cut:

    echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2
    

    More generic:

    INPUT='someletters_12345_moreleters.ext'
    SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
    echo $SUBSTRING
    
    0 讨论(0)
  • 2020-11-22 11:21

    A bash solution:

    IFS="_" read -r x digs x <<<'someletters_12345_moreleters.ext'
    

    This will clobber a variable called x. The var x could be changed to the var _.

    input='someletters_12345_moreleters.ext'
    IFS="_" read -r _ digs _ <<<"$input"
    
    0 讨论(0)
提交回复
热议问题