Как хранение регулярного выражения в переменной оболочки позволяет избежать проблем с цитированием символов, которые являются специальными для оболочки?

sudo vim -S /home/user/.vimrc /etc/rc.conf

Это эквивалентно:

sudo vim / etc /rc.conf + : source /home/user/.vimrc

и также может иметь псевдоним:

alias svim = 'sudo vim -S /home/user/.vimrc'

10
14.02.2019, 22:46
2 ответа

La única forma de hacer coincidir una cadena explícita es citarla:

[[ $var =~ 'quux' ]]

Incluso si la cadena contiene caracteres especiales (especiales para el shell [a])
sin que el caparazón los expanda o los interprete [b]:

$ var='^abcd'
$ [[ $var =~ '^ab' ]] && echo yes || echo no
yes

Si realmente necesitamos permitir (shell )caracteres especiales y permitir que el shell los interprete como una expresión regular, no deberían -entrecomillarse.

$ var='abcd'
$ [[ $var =~ ^ab ]] && echo yes || echo no
yes

Pero las cadenas sin comillas crean nuevos problemas, como con los espacios:

$ var='ab cd'
$ [[ $var =~ ^ab cd ]] && echo yes || echo no
bash: syntax error in conditional expression
bash: syntax error near `cd'

Para resolverlo, todavía necesitamos citar caracteres especiales:

$ var='ab cd'
$ [[ $var =~ ^"ab cd" ]] && echo yes || echo no
yes

$ [[ $var =~ ^ab\ cd ]] && echo yes || echo no
yes

Otros ejemplos:

[[ "a b"  =~  ^a\ b$ ]] && echo yes
[[ "a|b"  =~  ^a\|b$ ]] && echo yes
[[ "a&b"  =~  ^a\&b$ ]] && echo yes

Almacenar la expresión regular dentro de una variable evita todos esos problemas de cotización.

$ regex='^a b$'
$ [[ "a b" =~ $regex ]] && echo yes
yes

[un]Lista de caracteres especiales de shell(|&;()<>spacetabnewline).

[b]Esto es cierto desde la versión bash bash -3.2 -alfa (bajo "3.Nuevas funciones en Bash" título):

f. Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.


Copia de descripción ampliada de bash FAQ:

E14) Why does quoting the pattern argument to the regular expression matching conditional operator (=~) cause regexp matching to stop working?

In versions of bash prior to bash-3.2, the effect of quoting the regular expression argument to the [[ command's =~ operator was not specified. The practical effect was that double-quoting the pattern argument required backslashes to quote special pattern characters, which interfered with the backslash processing performed by double-quoted word expansion and was inconsistent with how the == shell pattern matching operator treated quoted characters.

In bash-3.2, the shell was changed to internally quote characters in single- and double-quoted string arguments to the =~ operator, which suppresses the special meaning of the characters special to regular expression processing ('.', '[', '\', '(', ')', '*', '+', '?', '{', '|', '^', and '$') and forces them to be matched literally. This is consistent with how the `==' pattern matching operator treats quoted portions of its pattern argument.

Since the treatment of quoted string arguments was changed, several issues have arisen, chief among them the problem of white space in pattern arguments and the differing treatment of quoted strings between bash-3.1 and bash-3.2. Both problems may be solved by using a shell variable to hold the pattern. Since word splitting is not performed when expanding shell variables in all operands of the [[ command, this allows users to quote patterns as they wish when assigning the variable, then expand the values to a single string that may contain whitespace. The first problem may be solved by using backslashes or any other quoting mechanism to escape the white space in the patterns.

Preguntas relacionadas:

Uso de una variable en una expresión regular

6
20.08.2021, 11:35

[[... ]]токенизация конфликтует с регулярными выражениями (подробнее об этом в мой ответ на ваш следующий -вопрос вверх\перегружен как оператор кавычек оболочки и оператор регулярного выражения (с некоторые помехи между ними в bash ), и даже когда нет очевидной причины для конфликта, поведение может быть неожиданным. Правила могут сбивать с толку.

Кто может сказать, что они будут делать, не попробовав (на всех возможных входных данных )с любой данной версией bash?

[[ $a = a|b ]]
[[ $a =~ a|b ]]
[[ $a =~ a&b ]]
[[ $a =~ (a|b) ]]
[[ $a =~ ([)}]*) ]]
[[ $a =~ [/\(] ]]
[[ $a =~ \s+ ]]
[[ $a =~ ( ) ]]
[[ $a =~ [ ] ]]
[[ $a =~ ([ ]) ]]

Вы не можете заключать регулярные выражения в кавычки, потому что если вы это сделаете, начиная с bash 3.2 и если совместимость с bash 3.1 не включена, цитирование регулярных выражений удаляет особое значение оператора RE. Например,

[[ $a =~ 'a|b' ]]

Соответствует, если $aсодержит только литерал a|b.

Сохранение регулярного выражения в переменной позволяет избежать всех этих проблем, а также делает код совместимым с ksh93иzsh(при условии, что вы ограничиваетесь POSIX ERE):

regexp='a|b'
[[ $a =~ $regexp ]] # $regexp should *not* be quoted.

В синтаксическом анализе/разметке этой команды оболочки нет двусмысленности, а используемое регулярное выражение хранится в переменной без какого-либо преобразования.

12
20.08.2021, 11:35

Теги

Похожие вопросы