Reines bash
, nein basename
, kein Jonglieren mit Variablen. Setzen Sie eine Zeichenfolge und echo
:
p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"
Salida:
foo
Anmerkung: Die bash
extglob muss die Option "on" sein, ( Ubuntu setzt extglob "on" standardmäßig), wenn nicht, tun:
shopt -s extglob
Ein Spaziergang durch die ${p//+(*\/|.*)}
:
${p
-- beginnen Sie mit $p .
//
jede Instanz des folgenden Musters ersetzen.
+(
Spiel eine oder mehrere der Musterliste in Klammern, ( d.h. bis Punkt #7 unten).
- 1. Muster:
*\/
passt auf alles, was vor einem wörtlichen " /
" Zeichen.
- Schablonentrenner
|
die in diesem Fall wie eine logisches ODER .
- 2. Muster:
.*
passt auf alles nach einem wörtlichen " .
" - das heißt, in bash
die " .
" ist nur ein Punktzeichen, und no ein Regex-Punkt .
)
Ende Musterliste .
}
Parametererweiterung beenden. Bei einer Stringsubstitution gibt es normalerweise eine weitere /
gefolgt von einer Ersatzzeichenfolge. Aber da es keine /
dort werden die übereinstimmenden Muster durch nichts ersetzt; dadurch werden die Übereinstimmungen gelöscht.
Einschlägige man bash
Hintergrund:
- Mustersubstitution :
${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pat
tern just as in pathname expansion. Parameter is expanded and
the longest match of pattern against its value is replaced with
string. If pattern begins with /, all matches of pattern are
replaced with string. Normally only the first match is
replaced. If pattern begins with #, it must match at the begin
ning of the expanded value of parameter. If pattern begins with
%, it must match at the end of the expanded value of parameter.
If string is null, matches of pattern are deleted and the / fol
lowing pattern may be omitted. If parameter is @ or *, the sub
stitution operation is applied to each positional parameter in
turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the substitution
operation is applied to each member of the array in turn, and
the expansion is the resultant list.
- erweiterter Mustervergleich :
If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized. In the following
description, a pattern-list is a list of one or more patterns separated
by a |. Composite patterns may be formed using one or more of the fol
lowing sub-patterns:
?(pattern-list)
Matches zero or one occurrence of the given patterns
*(pattern-list)
Matches zero or more occurrences of the given patterns
+(pattern-list)
Matches one or more occurrences of the given patterns
@(pattern-list)
Matches one of the given patterns
!(pattern-list)
Matches anything except one of the given patterns