我是tcl的新手,我尝试在split命令中使用 我的目标是访问路径并删除temp.txt中写的行号
//this block was successful
set f [open wave_test.txt]
set pid [open temp.txt "w+"]
while {[gets $f line] != -1} {
if {[regexp {#spg_backref :\s+(.*)} $line all value]} {
puts $pid $value
}
}
close $f
//here I have a problem while printing the value of data that doesn't exist
in the temp.txt file
set data [split $pid "\n"]
puts "the data is $data\n"
close $pid
//I think that there is a problem using " as a token in split command
foreach line $data {
puts "set my list\n"
set my_list [split $line ""]
puts "my_list is $my_list\n"
set path [lindex $my_list 1]
set line_num [lindex $my_list 1]
puts "the path is $path\n"
puts "the line number is $line_num\n"
}
//I copied some lines from the temp.txt file
"/c/pages/smelamed/glass/var/tests/my_glass/rules/top.txt" 1145
"/c/pages/smelamed/glass/var/tests/my_glass/rules/target.txt" 114
"/c/pages/smelamed/glass/var/tests/my_glass/rules/other.txt" 3
谢谢!
答案 0 :(得分:1)
在set data [split $pid "\n"]
行中,$ pid是打开的“ temp.txt”文件的文件句柄,不是 内容文件
打开文件w +之后,就可以
# write to the file
...
# jump to beginning of file and read it
seek $pid 0
set data [split [read -nonewline $pid] \n]
close $pid
答案 1 :(得分:0)
split $line ""
表示将$line
拆分为单独的字符列表。因此,如果您有字符串“ abc”,那么set mylist [split abc ""]
将给出{a b c},而lindex $mylist 1
等于'b'。只需编写:set path [lindex $line 0]
,因为lindex
会自动将$line
解释为列表。
如果路径名包含空格,则使用split $line
可能会导致错误。
您还可以考虑使用lassign $line path line_num
在一个命令中同时设置path
和line_num
。