• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

regex

Using Or on Regular Expressions

January 21, 2021 by Ulysses

Here’s a regex using the pipe symbol as OR to allow only 6 possible values.

regex="efs-(00|04|08|12|16|20)00"

regex="efs-(00|04|08|12|16|20)00"

Matches:

efs-0000
efs-0400
efs-0800
efs-1200
efs-1600
efs-2000

efs-0000 efs-0400 efs-0800 efs-1200 efs-1600 efs-2000

No matches:

efs-0100
efs-2200
efs-0600
efs-1400
efs-1800
efs-1110
111022
asdb023
2330asd
1200-efs
1205
abc

efs-0100 efs-2200 efs-0600 efs-1400 efs-1800 efs-1110 111022 asdb023 2330asd 1200-efs 1205 abc

$var is compared with $regex to find a match. $var is any of the variables above.

if [[ $var != $regex ]]; then
  echo "Not a match"
else
  echo "It's a match"
fi

if [[ $var != $regex ]]; then echo "Not a match" else echo "It's a match" fi

Filed Under: Linux Tagged With: or, regex, regular expressions

Regex Match

January 19, 2019 by Ulysses

Regex is really cool. You can do amazing things with it, but if you’re starting new, it’s quite daunting task. If you ever find one that works, you better hang on to it for dear life. Here’s one that I know is working. It reads data from a file, and compares and matches a variable to a certain pattern. In the example below, the variable I’m searching for, must contain a string with the following characters “server-w.” They also must be followed by at least one number or a set of numbers.

cat filename | while read LINE; do
  if [[ $LINE =~ server-w-*.[0-9] ]]; then
     echo "Do not backup $LINE"
  else
     echo "Backup $LINE"
  fi
done

cat filename | while read LINE; do if [[ $LINE =~ server-w-*.[0-9] ]]; then echo "Do not backup $LINE" else echo "Backup $LINE" fi done

If you need help with Regex, check out a couple of sites below that allows you to test your regex skills. Regex and RegExr.

Filed Under: Linux Tagged With: bash, matching, regex, regular expressions

  • Home
  • About
  • Archives

Copyright © 2012–2022