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

variables-反向正则表达式模式匹配

(variables - Reverse regex pattern match)

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

我有一个简单的函数来查找以Bash编写的跟踪数字,并且有效。我为每个模式变化定义了几个变量。然后egrep我使用来搜索文件,然后输出匹配项。我想做的是知道匹配的模式,这样我就可以将其识别为输出的一部分。

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
}

我想知道哪个变量($usps1$usps2等)提供了匹配项,这样我就可以使输出说The USPS Tracking # is...The FedEx Tracking # is...

有没有办法确定匹配的是哪种模式?

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

使用grep -o刚刚得到的文件匹配的部分,然后与每个模式进行测试。

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