Warm tip: This article is reproduced from serverfault.com, please click

Reverse regex pattern match

发布于 2020-11-27 23:34:49

I have a simple function for looking up tracking numbers written in Bash that works. I've defined several variables for each pattern variation. I then use egrep to search the file and then output the match. What I'd like to do is know which pattern matched so I can identify it as part of the output.

function gettracking () {

local usps1='[0-9]{20}'
local usps2='[0-9]{4}[[:blank:]][0-9]{4}[[:blank:]]'
# there's several more, but not necessary for the question)

tracking=$(egrep "${usps1}|${usps2}" $1)

if [ -z "${tracking}-x" ]
then
  echo "No tracking found"
else 
  echo "Tracking # ${tracking} sent to clipboard"
  echo ${tracking} | pbcopy    # (this is on macOS BTW)
fi
}

I would like to know which of the variables ($usps1 or $usps2, etc.) provided the match so that I can make my output say The USPS Tracking # is... or The FedEx Tracking # is...

Is there a way to identify which pattern made the match?

Questioner
Allan
Viewed
0
Barmar 2020-11-28 07:53:09

Use grep -o to just get the matched part of the file, then test it with each pattern.

match=$(grep -o "${usps1}|${usps2}" $1)
if [[ $match =~ $usps1 ]]
then echo "The USPS tracking number is $tracking"
elif [[ $match =~ $usps2 ]]
then echo "The FedEx tracking number is $tracking"
fi