我这里有一个文件,它有多个set语句.但是,我想提取我感兴趣的行.以下代码可以提供帮助吗?
set in [open filename r]
seek $in 0 start
while{ [gets $in line ] != -1} {
regexp (line to be extracted)
}
Run Code Online (Sandbox Code Playgroud)
其他方案:
而不是使用gets我更喜欢使用read函数来读取文件的整个内容,然后逐行处理.因此,我们通过将其作为行列表完全控制文件操作
set fileName [lindex $argv 0]
catch {set fptr [open $fileName r]} ;
set contents [read -nonewline $fptr] ;#Read the file contents
close $fptr ;#Close the file since it has been read now
set splitCont [split $contents "\n"] ;#Split the files contents on new line
foreach ele $splitCont {
if {[regexp {^set +(\S+) +(.*)} $ele -> name value]} {
puts "The name \"$name\" maps to the value \"$value\""
}
}
Run Code Online (Sandbox Code Playgroud)
如何运行此代码:
说上面的代码保存在test.tcl
Then中
tclsh test.tcl FileName
Run Code Online (Sandbox Code Playgroud)
FileName 是文件的完整路径,除非该文件与程序所在的目录相同.
| 归档时间: |
|
| 查看次数: |
21929 次 |
| 最近记录: |