我正在使用 tcl 执行一些模式匹配。以下是我正在执行匹配的字符串:
ps -ef | grep ipqosmgr
root 17255 17136 0 22:34 ttyS0 00:00:00 grep ipqosmgr
root 28986 17731 0 Jun05 ? 00:02:01 /isan/bin/ipqosmgr
通常我想要第三行
root 28986 17731 0 Jun05 ? 00:02:01 /isan/bin/ipqosmgr
因为我想要与该进程关联的进程 ID。
当我使用以下正则表达式时,它按预期工作:
% foreach line [split $output \n] {
if { [ regexp -nocase {root\s+([0-9]+)\s+.*(/isan/bin/ipqosmgr)} $line - value ] } {
puts $line
}
}
root 28986 17731 0 Jun05 ? 00:02:01 /isan/bin/ipqosmgr
% puts $value
28986
%
但是,我希望这段代码能够为多个进程运行,因此将其放入带有 $process 的函数中,该函数将保存进程的值。当我对变量 $process 使用相同的正则表达式时,它会失败。
% puts $process
ipqosmgr
%
% foreach line [split $output \n] {
if { [ regexp -nocase {root\s+([0-9]+)\s+.*(/isan/bin/$process)} $line - value ] } {
puts $line
}
}
%
% puts $value
can't read "value": no such variable
%
我不知道为什么它会这样,如果有人能告诉我这里出了什么问题以及如何纠正它,那就太好了。
最佳答案
您可以使用 format
准备正则表达式如下:
foreach line [split $output \n] {
set regex [format {root\s+([0-9]+)\s+.*(/isan/bin/%s)} $process]
if { [ regexp -nocase $regex $line - value ] } {
puts $line
}
}
使用表达式的方式的问题是大括号阻止变量替换,虽然您可以使用引号代替正则表达式,但您必须转义大量字符(例如方括号、反斜杠)并且为了避免必须转义这些,使用 format
可以更简单地使用。
关于regex - 与变量名一起使用时,tcl 正则表达式无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50735772/