file - 处理包含不匹配大括号的文件

标签 file tcl curly-braces

我需要修改一个包含多行且大括号不匹配的文件,例如:

  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/

相关文章:

java - 为什么 Java 数组声明使用大括号?

c++ - Ifstream 文件没有打开,尽管一切似乎都已到位 (c++)

tcl - 预期中的 “send_user”和 “puts”有什么区别?

javascript - 如何使用 javascript 在正则表达式替换中表示大括号

tcl - 用TCL编写程序

regex - 在 tcl 脚本中使用 awk

java - Visual Studio Code java格式文档大括号换行

excel - Excel 数据连接的相对文件路径

c# - C#从文本文件中读取数字

javascript - 我如何判断一个 Javascript 对象是否是一个文件?