Extract substring in Bash

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

    Generic solution where the number can be anywhere in the filename, using the first of such sequences:

    number=$(echo $filename | egrep -o '[[:digit:]]{5}' | head -n1)
    

    Another solution to extract exactly a part of a variable:

    number=${filename:offset:length}
    

    If your filename always have the format stuff_digits_... you can use awk:

    number=$(echo $filename | awk -F _ '{ print $2 }')
    

    Yet another solution to remove everything except digits, use

    number=$(echo $filename | tr -cd '[[:digit:]]')
    

提交回复
热议问题