如何grep方括号内的参数? [英] How to grep parameters inside square brackets?
问题描述
你能帮我写下下面的脚本吗?
Could you please help me with the following script?
这是 Synopsys IC Compiler II 将提供的 Tcl 脚本.
It is a Tcl script which Synopsys IC Compiler II will source.
set_dont_use [get_lib_cells */*CKGT*0P*] -power
set_dont_use [get_lib_cells */*CKTT*0P*] -setup
我可以知道如何只取 */*CKGT*0P*
和 */*CKTT*0P*
并将它们分配给一个变量.
May I know how to take only */*CKGT*0P*
and */*CKTT*0P*
and assign these to a variable.
推荐答案
当然,您可以将 Tcl 脚本视为您搜索的内容;毕竟它只是一个包含文本的文件.
Of course you can treat a Tcl script as something you search through; it's just a file with text in it after all.
让我们编写一个脚本来选择文本.当然,这将是一个 Tcl 脚本.为了可读性,我将把正则表达式本身放在一个全局变量中;把它当作一个常数.(在较大的脚本中,我发现给 RE 起这样的名字很有帮助,因为这些名字可以用来提醒我正则表达式的目的.我称之为<代码>RE"在这里.)
Let's write a script to select the text out. It'll be a Tcl script, of course. For readability, I'm going to put the regular expression itself in a global variable; treat it like a constant. (In larger scripts, I find it helps a lot to give names to REs like this, as those names can be used to remind me of the purpose of the regular expression. I'll call it "RE
" here.)
set f [open theScript.tcl]
# Even with 10 million lines, modern computers will chew through it rapidly
set lines [split [read $f] "\n"]
close $f
# This RE will match the sample lines you've told us about; it might need tuning
# for other inputs (and knowing what's best is part of the art of RE writing)
set RE {^set_dont_use \[get_lib_cells ([\w*/]+)\] -\w+$}
foreach line $lines {
if {[regexp $RE $line -> term]} {
# At this point, the part you want is assigned to $term
puts "FOUND: $term"
}
}
上面 RE 中的关键内容?大括号是为了减少反斜杠炎.文字方括号被反斜杠.括号中的位是我们捕获到 term
变量中的位.[\w*/]+
匹配由标准 word 字符"加上 *
和/
.
The key things in the RE above? It's in braces to reduce backslash-itis. Literal square brackets are backslashed. The bit in parentheses is the bit we're capturing into the term
variable. [\w*/]+
matches a sequence of one or more characters from a set consisting of "standard word characters" plus *
and /
.
regexp
的使用将 ->
作为一个被忽略的变量的有趣名称.我可以称它为 dummy
代替;当 RE 匹配时,它将在其中包含整个匹配的字符串,但是我们已经在 $term
中包含了,因为我们使用的是完全锚定的 RE.但我喜欢使用 ->
作为将子匹配分配给这些"的助记符.另外,regexp
的正式结果是 RE 匹配的次数;如果没有 -all
选项,这实际上是一个布尔值,在匹配时准确为真,这很有用.非常有用.
The use of regexp
has ->
as a funny name for a variable that is ignored. I could have called it dummy
instead; it's going to have the whole matched string in it when the RE matches, but we already have that in $term
as we're using a fully-anchored RE. But I like using ->
as a mnemonic for "assign the submatches into these". Also, the formal result of regexp
is the number of times the RE matched; without the -all
option, that's effectively a boolean that is true exactly when there was a match, which is useful. Very useful.
这篇关于如何grep方括号内的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!