# 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`.
这实际上是什么意思? 我能得到一个例子
答案 0 :(得分:1)
你引用的解释并不准确。此机制允许您从变量的值中删除前缀或后缀。
vnix$ v=foobar
vnix$ echo "${v#foo}"
bar
vnix$ echo "${v%bar}"
foo
表达式可以是glob,因此您不限于静态字符串。
vnix$ echo "${v%b*}"
foo
还有##和%%来修剪最长的匹配而不是最短的匹配。
答案 1 :(得分: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!
答案 2 :(得分:1)
问题中引用的文字是一个可怕的解释。以下是the sh language standard的文字:
${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.