Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regular expressions: Matching numbers 0-1000 [duplicate]

I'm writing a script that executes scripts stored in a given directory, based on an array containing the filenames of the scripts. Here's a section of my 'menu', just to clarify:

#######

Title: Test script 1
Description: Test script 1
To execute: 0

#######

Title: Test script 2
Description: Test script 2
To execute: 1

#######

I have an array named array that contains the names of the scripts with an index corresponding to the printed value under "to execute". Right now, I'm using a case statement to handle input and provide an exit option.

case $REPLY in 
     [Ee]) clear
           exit;;
     [[:digit:]] $scriptDirectory/${array[$REPLY]}

However, the [[:digit:]] expression only matches 0-9. I need a regex that works in the case statement that matches 0-999, or similar.

like image 843
Thorne Garvin Avatar asked Mar 12 '23 07:03

Thorne Garvin


2 Answers

case only uses globs (aka filename expansion patterns), not regular expressions.

You can set extended glob with shopt -s extglob, then you can use +() to match one or more occurrence :

shopt -s extglob

case $REPLY in 
     [Ee]) clear
           exit;;
     +([[:digit:]])) $scriptDirectory/${array[$REPLY]};;
esac

Note : I added missing ) after your second case pattern and missing ;; at the end of the same line. Also added the esac missing statement.

Update :

If you just want to match numbers between 0 and 999, try this :

     [0-9]?([0-9])?([0-9]))  $scriptDirectory/${array[$REPLY]};;

Character range are used here as I find it a bit more readable. The result will be the same.

like image 183
SLePort Avatar answered Apr 08 '23 04:04

SLePort


The easiest way I've found is bash is:

^(1000|[0-9]{1,3})$

Using this regex combined with the =~ operator (which interprets the string to the right as an extended regular expression) you can construct a simple test. (with your input as "$1")

if [[ $1 =~ ^(1000|[0-9]{1,3})$ ]]; then
    echo "0 <= $1 <= 1000 (1)"
else
    echo "$1 - invalid number"
fi

Example Use/Output

$ for i in -10 -1 0 1 10 100 999 1000 1001; do ./zero1thousand.sh $i; done
-10 - invalid number
-1 - invalid number
0 <= 0 <= 1000
0 <= 1 <= 1000
0 <= 10 <= 1000
0 <= 100 <= 1000
0 <= 999 <= 1000
0 <= 1000 <= 1000
1001 - invalid number
like image 36
David C. Rankin Avatar answered Apr 08 '23 04:04

David C. Rankin