我需要修改一个包含多行且大括号不匹配的文件,例如:
rmsd {
atoms {
atomsFile
atomsCol B
atomsColValue 1
}
所以如果我这样做:
set fp [open "fpor.conf" r]
set file_data [read $fp]
close $fp
set confFile [split $file_data "\n"]
set inOut [open "us.in" w]
foreach line $inFile {
if {[lindex $line 0] == "atomsFile"} {
lappend line "us.pdb"
}
puts $inOut "$line"
}
close $inOut
脚本失败并出现以下错误: 列表中不匹配的左大括号。有办法避免这种情况吗?
最佳答案
您将文件读入行列表中,然后迭代这些行。您的错误是将行视为列表而不是字符串。这将帮助您:
foreach line $confFile {
set fields [regexp -all -inline {\S+} $line]
if {[lindex $fields 0] eq "atomsFile"} { ...
此处,
split
不足以查找以空格分隔的单词,因为split
会按单个字符进行拆分:% set line { atomsFile } atomsFile % split $line {} {} {} {} {} {} atomsFile {}
或者只是进行正则表达式匹配:
foreach line $confFile {
if {[regexp {^\s*atomsFile} $line]} { ...
正如您所注意到的,您不能像处理列表一样处理任意字符串。
% set line "no { match here"
no { match here
% lindex $line 0
unmatched open brace in list
% lindex [split $line] 0
no
关于file - 处理包含不匹配大括号的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47834116/