Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Regex to check if first character of string is a number

Tags:

regex

bash

shell

I'm writing a script that uses trace route. I'm iterating through each line of the trace route and then through each word (separated by whitespace). However, sometimes the trace route returns a * character, which causes issues when echoing (filenames are output).

I've been fiddling with RegEx and so far I've come up with this:

if [[ $item =~ ^\d ]];

Item is a portion of the trace route.

For each item in a trace route line, I would simply like to check if the first character is equal to a number or not, then continue accordingly.

like image 709
S_W Avatar asked Dec 10 '22 17:12

S_W


2 Answers

\d is not supported in POSIX Regular Expressions (used by Bash). You need to replace it with [0-9] like so:

if [[ $item =~ ^[0-9] ]];

Check out this StackOverflow answer

Could also use [:digit:] to make it easier to read:

if [[ $item =~ ^[[:digit:]] ]];
like image 63
Kaspar Lee Avatar answered Feb 15 '23 10:02

Kaspar Lee


No need to use regex just glob is sufficient:

[[ $item == [0-9]* ]] && echo "it starts with a digit"

You can also use:

[[ $item == [[:digit:]]* ]]
like image 33
anubhava Avatar answered Feb 15 '23 12:02

anubhava