match() 函数的功能是在字串中查找正则匹配并返回其位置,它的原型如下:其中 string 是要搜索的字串,regexp 是一个正则表达式,即按照正则来搜索 string 以查找相应的匹配。如果找到,那么返回其位置(从 1 开始),如果没找到,那么返回 0 。另外,match 函数会设置两个内置变量:RSTART 和 RLENGTH。RSTART 也就是索引值(位置),而 RLENGTH 表示正则匹配的子串长度。
测试代码:
[Bash shell] 纯文本查看 复制代码 {
if ($1 == "FIND")
regex = $2
else {
where = match($0, regex)
if (where) {
print "---------------------------------"
print "Match of", regex, "found at", where, "in", $0
print "RSTART variable is " RSTART
print "RLENGTH variable is " RLENGTH
}
}
}
供测试文本:# cat match.txt
FIND g.*d
welcome to groad forum.
Join it and share your ideas!
FIND m.*y
hello linux world.
groad is a forum mainly for linux. 运行输出:# awk -f match.awk match.txt
---------------------------------
Match of g.*d found at 12 in welcome to groad forum.
RSTART variable is 12
RLENGTH variable is 5
---------------------------------
Match of m.*y found at 16 in groad is a forum mainly for linux.
RSTART variable is 16
RLENGTH variable is 8 上面的代码中,$0 表示整个记录。首先当 $1 匹配 FIND 后,那么就将正则赋值给变量 regex 。那么在下一行判断时,if 语句成立,于是打印相关的内容。注意第 2 个匹配 m.*y 中的 m 从 forum 中的 m 那里开始。 |