/ / Perché questo comando sed emette "[18" invece di "18"? - regex, unix, sed, sostituzione delle stringhe

Perché questo comando sed emette "[18" invece di "18"? - regex, unix, sed, sostituzione delle stringhe

echo [18%] | sed s:[[%]]::g

Sono davvero confuso da questo, perché lo stesso modello esatto sostituisce con successo [18%] in vim. Ho anche testato l'espressione in alcuni strumenti di regex online e tutti dicono che corrisponderà al [, %, e ] come inteso. Ho provato ad aggiungere il -r opzione e circonda il comando di sostituzione tra virgolette.

So che ci sono altri comandi che potrei usare per svolgere questo compito, ma voglio sapere perché si sta comportando in questo modo in modo da ottenere una migliore comprensione di sed.

risposte:

6 per risposta № 1
$ echo [18%] | sed s:[][%]::g
18

sed supporta la sintassi dell'espressione regolare POSIX.2: sintassi di base (BRE) per impostazione predefinita, sintassi estesa con -r bandiera. Nella sintassi POSIX.2, base o estesa, si include una parentesi quadra destra rendendola il primo carattere nella classe di caratteri. Le barre rovesciate non aiutano.

Questo è fastidioso perché quasi tutti gli altri linguaggi e strumenti moderni usano la sintassi regex del Perl o del Perl. La sintassi POSIX è un anacronismo.

Puoi leggere la sintassi POSIX.2 nella pagina man 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.