1
  # The **variable slicing** notation in the following conditional
  # needs some explanation: `${var#expr}` returns everything after
  # the match for 'expr' in the variable value (if any), and
  # `${var%expr}` returns everything that doesn't match (in this
  # case, just the very first character. You can also do this in
  # Bash with `${var:0:1}`, and you could use cut too: `cut -c1`.

这实际上意味着什么?我能举个例子吗

4

3 回答 3

1

这是一个简单的例子:

#!/bin/bash

message="hello world!"
var1="hello"
var2="world!"
echo "${message#$var1}"
echo "${message%$var2}"
echo "${message%???}"
echo "${message}"

输出:

 world!
hello 
hello wor
hello world!
于 2012-11-22T21:03:52.030 回答
1

你引用的解释根本不准确。此机制允许您从变量的值中删除前缀或后缀。

vnix$ v=foobar
vnix$ echo "${v#foo}"
bar
vnix$ echo "${v%bar}"
foo

表达式可以是一个 glob,因此您不限于静态字符串。

vnix$ echo "${v%b*}"
foo

还有 ## 和 %% 来修剪最长的匹配而不是最短的匹配。

于 2012-11-22T21:03:04.623 回答
1

问题中引用的文字是一个糟糕的解释。这是来自sh 语言标准的文本:

${parameter%word}
    Remove Smallest Suffix Pattern. The word shall be expanded to produce a pattern.
    The parameter expansion shall then result in parameter, with the smallest portion
    of the suffix matched by the pattern deleted.
${parameter%%word}
    Remove Largest Suffix Pattern. The word shall be expanded to produce a pattern. 
    The parameter expansion shall then result in parameter, with the largest portion
    of the suffix matched by the pattern deleted.
${parameter#word}
    Remove Smallest Prefix Pattern. The word shall be expanded to produce a pattern.
    The parameter expansion shall then result in parameter, with the smallest portion
    of the prefix matched by the pattern deleted.
${parameter##word}
    Remove Largest Prefix Pattern. The word shall be expanded to produce a pattern.
    The parameter expansion shall then result in parameter, with the largest portion
    of the prefix matched by the pattern deleted. 
于 2012-11-23T16:19:54.640 回答