echo [18%] | sed s:[[%]]::g
Ich bin wirklich verwirrt, weil dasselbe Muster erfolgreich ersetzt [18%]
in vim. Ich habe den Ausdruck auch in ein paar Online - Regex - Tools getestet, und alle sagen, dass er mit dem übereinstimmen wird [
, %
, und ]
wie beabsichtigt. Ich habe versucht, die -r
Option sowie das Ersetzen des Befehls in Anführungszeichen.
Ich weiß, dass es andere Befehle gibt, mit denen ich diese Aufgabe erledigen könnte, aber ich möchte wissen, warum es sich so verhält, um Sed besser zu verstehen.
Antworten:
6 für die Antwort № 1$ echo [18%] | sed s:[][%]::g
18
sed unterstützt die POSIX.2-Syntax für reguläre Ausdrücke -r
Flagge. In der POSIX.2-Syntax, basic oder extended, schließen Sie eine rechte eckige Klammer ein, indem Sie sie zum ersten Zeichen in der Zeichenklasse machen. Backslashes helfen nicht.
Dies ist ärgerlich, da fast alle anderen modernen Sprachen und Tools Perl oder Perl-ähnliche Regex-Syntax verwenden. Die POSIX-Syntax ist ein Anachronismus.
Informationen zur POSIX.2-Syntax finden Sie in der Manpage regex (7).
A bracket expression is a list of characters enclosed in "[]". It normally
matches any single character from the list (but see below). If the list begins
with "^", it matches any single character (but see below) not from the rest of
the list. If two characters in the list are separated by "-", this is shorthand
for the full range of characters between those two (inclusive) in the collating
sequence, for example, "[0-9]" in ASCII matches any decimal digit. It is ille‐
gal(!) for two ranges to share an endpoint, for example, "a-c-e". Ranges are
very collating-sequence-dependent, and portable programs should avoid relying on
them.
To include a literal "]" in the list, make it the first character (following a
possible "^"). To include a literal "-", make it the first or last character, or
the second endpoint of a range. To use a literal "-" as the first endpoint of a
range, enclose it in "[." and ".]" to make it a collating element (see below).
With the exception of these and some combinations using "[" (see next para‐
graphs), all other special characters, including "", lose their special signifi‐
cance within a bracket expression.