Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GREP: variable in regular expression

Tags:

regex

grep

bash

If I want to look whether a string is alphanumeric and shorter than a certain value, say 10, I would do like this (in BASH+GREP):

if grep '^[0-9a-zA-Z]\{1,10\}$' <<<$1 ; then ...

(BTW: I'm checking for $1, i.e. the first argument)

What if I want the value 10 to be written on a variable, e.g.

UUID_LEN=10
if grep '^[0-9a-zA-Z]\{1,$UUID_LEN\}$' <<<$1 ; then ...

I tried all sort of escapes, braces and so on, but could not avoid the error message

grep: Invalid content of \{\}

After googling and reading bash and grep tutorials I'm pretty convinced it can't be done. Am I wrong? Any way to go around this?

like image 773
KeinReverb Leonardo Gabrielli Avatar asked Dec 02 '25 09:12

KeinReverb Leonardo Gabrielli


1 Answers

You need to use double quotes so that the shell expands the parameter before passing the resulting argument to grep:

if grep "^[0-9a-zA-Z]\{1,$UUID_LEN\}$" <<<$1 ; then ...

bash can perform regular expression matching itself, without having to start another process to run grep:

if [[ $1 =~ ^[0-9a-zA-Z]{1,$UUID_LEN}$ ]]; then
like image 58
chepner Avatar answered Dec 04 '25 01:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!