Extract substring in Bash

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

    In case someone wants more rigorous information, you can also search it in man bash like this

    $ man bash [press return key]
    /substring  [press return key]
    [press "n" key]
    [press "n" key]
    [press "n" key]
    [press "n" key]
    

    Result:

    ${parameter:offset}
           ${parameter:offset:length}
                  Substring Expansion.  Expands to  up  to  length  characters  of
                  parameter  starting  at  the  character specified by offset.  If
                  length is omitted, expands to the substring of parameter  start‐
                  ing at the character specified by offset.  length and offset are
                  arithmetic expressions (see ARITHMETIC  EVALUATION  below).   If
                  offset  evaluates  to a number less than zero, the value is used
                  as an offset from the end of the value of parameter.  Arithmetic
                  expressions  starting  with  a - must be separated by whitespace
                  from the preceding : to be distinguished from  the  Use  Default
                  Values  expansion.   If  length  evaluates to a number less than
                  zero, and parameter is not @ and not an indexed  or  associative
                  array,  it is interpreted as an offset from the end of the value
                  of parameter rather than a number of characters, and the  expan‐
                  sion is the characters between the two offsets.  If parameter is
                  @, the result is length positional parameters beginning at  off‐
                  set.   If parameter is an indexed array name subscripted by @ or
                  *, the result is the length members of the array beginning  with
                  ${parameter[offset]}.   A  negative  offset is taken relative to
                  one greater than the maximum index of the specified array.  Sub‐
                  string  expansion applied to an associative array produces unde‐
                  fined results.  Note that a negative offset  must  be  separated
                  from  the  colon  by  at least one space to avoid being confused
                  with the :- expansion.  Substring indexing is zero-based  unless
                  the  positional  parameters are used, in which case the indexing
                  starts at 1 by default.  If offset  is  0,  and  the  positional
                  parameters are used, $0 is prefixed to the list.
    

提交回复
热议问题