【问题标题】:Expression after last specific character最后一个特定字符后的表达式
【发布时间】:2012-03-02 11:39:33
【问题描述】:
foo="/sdf/here/jfds"
bar="${foo##*/}"

谁能解释“${foo##*/}”表达式的工作原理?我知道它会在最后一个正斜杠(即jfds)之后返回字符串。但是,我不知道它是怎么做的,也不知道这种表达方式叫什么?

【问题讨论】:

  • 它叫做parameter expansion。该链接还解释了“它是如何工作的”,即描述它的作用。或者您对此有更具体的问题?

标签: linux bash shell unix scripting


【解决方案1】:

它是几个 shell 功能之一,通常称为 shell 扩展。这种特殊的扩展被称为参数扩展*。

您可以将这种特殊的 shell 扩展形式视为 left-truncate 字符串函数。您必须使用如图所示的大括号(这不是可选的)..

当你只使用一个#时,这意味着只左截断后面模式的第一个出现(直到结束}。当你使用两个##时,这意味着左截断所有连续模式匹配。var="a/b/c"; echo ${var#*/}的结果是b/c...echo ${var##*/}返回c

有一个互补的右截断。它使用% 而不是#...(我“记住”这是因为# 就像一个bash 评论;总是在左边)。

* 被视为 bash 通配符扩展。

这里是所有 shell 扩展的列表,按优先顺序显示。

展开顺序为:

1. brace expansion ... prefix{-,\,}postfix             # prefix-postfix prefix,postfix
                    .. {oct,hex,dec,bin}               # oct hex dec bin
                     . {a..b}{1..2}                    # a1 a2 b1 b2
                     . {1..04}                         # 01 02 03 04
                     . {01..4}                         # 01 02 03 04
                     . {1..9..2}                       # 1 3 5 7 9
                     . \$\'\\x{0..7}{{0..9},{A..F}}\'  # $'\x00' .. $'\x7F'     

2. tilde expansion .... ~           # $HOME
                    ... ~axiom      # $(dirname "$HOME")/axiom  
                    ... ~fred       # $(dirname "$HOME")/fred
                     .. ~+          # $PWD     (current working directory)
                     .. ~-          # $OLDPWD  (previous working directory. If OLDPWD is unset,
                                                        ~- is not expanded. ie. It stays as-is,
                                                          regardless of the state of nullglob.)
                                    # Expansion for Directories in Stack. ie. 
                                    # The list printed by 'dirs' when invoked without options 
                      . ~+N         #    Nth directory in 'dirs' list (from LHS)
                      . ~-N         #    Nth directory in 'dirs' list (from RHS)

3. parameter expansion .... ${VAR/b/-dd-}  
                        ... ${TEST_MODE:-0}
                         .. ${str: -3:2}  # note space after :
                          . ${#string}

4. (processed left-to-right) 
     variable expansion 
     arithmetic expansion
     command substitution

▶5. word splitting          # based on $IFS (Internal Field Seperator)

▷6. pathname expansion
      according to options such as:   
      nullglob, GLOBIGNORE, ...and more

# Note: ===============
▶ 5. word splitting     ↰ 
▷ 6. pathname expansion ↰  
# =====================  ↳  are not performed on words between  [[  and  ]]

【讨论】:

    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多