使用“读取文件”;[“和”操作每行TCL

使用“读取文件”;[“和”操作每行TCL,tcl,Tcl,我有以下行的文件(file.list): insert_buffer [get_ports { port }] BUFF1 -new_net net -new_cell cell #! /usr/local/bin/tclsh foreach arg $argv { set file [open $arg r] set data [ read $file ] foreach line [ split $data "\n" ] { puts $line set name [l

我有以下行的文件(file.list)

insert_buffer [get_ports { port }] BUFF1 -new_net  net -new_cell cell
    #! /usr/local/bin/tclsh
foreach arg $argv {

set file [open $arg r]
set data [ read $file ]

foreach line  [ split $data "\n" ] {

puts $line

set name [lindex $line [expr [lsearch -all $line "-new_cell"]+1]]
puts $name
}

close $file

} 
我正在用下面的脚本(read.tcl)读取文件:

insert_buffer [get_ports { port }] BUFF1 -new_net  net -new_cell cell
    #! /usr/local/bin/tclsh
foreach arg $argv {

set file [open $arg r]
set data [ read $file ]

foreach line  [ split $data "\n" ] {

puts $line

set name [lindex $line [expr [lsearch -all $line "-new_cell"]+1]]
puts $name
}

close $file

} 
运行上面的脚本(read.tcl file.list)时出现错误,因为file.list中有“[”,脚本认为这是tcl命令的开始

list element in braces followed by "]" instead of space
    while executing
"lsearch -all $line "-new_cell""
    ("foreach" body line 5)
    invoked from within
"foreach line  [ split $data "\n" ] {
如何正确读取文件并克服“[”符号

如何正确读取文件并克服“[”符号

我真的不明白您为什么要这样做(一个一个地处理一个Tcl脚本),但在提交给
lsearch
之前,您必须确保每一行都是有效的Tcl列表

lsearch -all [split $line] "-new_cell"

只有
split
将转换任意字符串(包含Tcl专用字符)进入有效的Tcl列表。

这是Tcl中为数不多的几次需要担心数据类型的情况之一。
$line
包含字符串。不要对字符串使用list命令,因为不能保证任意字符串是格式良好的列表

这样做:

set fields [split $line]
# don't use "-all" here: you want a single index, not a list of indices.
set idx [lsearch -exact $fields "-new_cell"]
if {$idx == -1} {
    do something here if there's no -new_cell in the line
} else {
    set name [lindex $fields $idx+1]
}

要对变量应用列表操作,它必须是有效的列表。变量
$line
不是有效的列表

最好使用
regexp
而不是
lsearch

regexp -- {-new_cell\s+(\S+)} $x match value
puts $value
输出:

cell

即使在读取文件中使用,我也需要在lsearch中使用split吗?您的第一个
split
生成一个行列表,需要第二个
split
将每个行字符串转换为行元素列表;因此,是的。