Search code examples
stringbashshellsubstring

Extract substring in Bash


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 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 am very interested in the number of different ways that this can be accomplished.


Solution

  • 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