需要使用 tcl 在输出文件中写入特定列

Need to write specific columns in output file using tcl

我正在尝试读取一个包含 5 列的文件(使用 space 定界符分隔)

#text  tag    x     y     data_lay

bad    bad1   10.0  10.0   L1

good   goodn  13.0  11.0   L1

并尝试在新文件的第一列上输出带有前缀的特定列。输出格式应如下所示

 Add_obj bad  10.0 10.0 L1

 Add_obj good 13.0 11.0 L1

我尝试了以下方法,但未能获得预期的输出。这是代码片段

set fp [open [lindex $argv 0] r]

set colData {}

while {[gets $fp line]>=0} {

    if {[llength $line] ==4 } {
   
        set colData [split $line “ “]
   
         puts “Add_obj [lindex $colData 0] [lindex $colData 2] [lindex $colData 3] [lindex $colData 4]”
   
    }
}

close $fp 

能否请您帮忙提供一个示例代码? 谢谢

  1. 不需要用 space 分割 $line。只要 $line 可以用作适当的列表,那么您就可以在 $line.

    上使用 lindex
  2. 我认为你只想在 llength 为 5(而不是 4)时打印。

  3. 我注意到在您的示例代码中有非 ascii 双引号 。您需要使用常规双引号 ".

set fp [open a.txt]

while {[gets $fp line]>=0} {

    if {[llength $line] == 5 } {
        # Skip header?
        if {[string match "#*" $line]} {
            continue
        }
        puts "Add_obj [lindex $line 0] [lindex $line 2] [lindex $line 3] [lindex $line 4]"
   
    }
}

close $fp 

您可能还想打印一个格式化的字符串,使用 format 命令准备。