tcl在列中添加数字直到模式不匹配

时间:2018-01-24 05:16:48

标签: tcl

嗨我需要在列中添加数字直到模式匹配,然后在模式匹配后开始添加数字,例如:

start 1   
start 2  
start 3  
pattern  
start 4    
start 5    
start 6    

我需要总和为6到模式和15后模式分别,我尝试regexp开始,但它添加第二列中的所有数字而不管'模式',我知道sed工作,但我需要仅在tcl-regexp中

1 个答案:

答案 0 :(得分:0)

如果您对当前代码的最小更改以及您当前的尝试/方法达到预期结果,我建议这样做:

set sum1 0
set sum2 0
set ind 0
set skip true

while {![eof $file]} {
  # Notice the change of $x to x here
  gets $file x
  if {[regexp start $x]} {
    set ind [lindex $x 1]
    # Depending on $skip, add the number to either sum1 or sum2
    if {$skip == "true"} {
      set sum1 [expr $sum1 + $ind]
    } else {
      set sum2 [expr $sum2 + $ind]
    }
  }
  if {[regexp pattern $x]} {
    set skip "false"
  }
}

puts $sum1
puts $sum2

尽管如此,我会使用以下内容使事情变得更简单:

set sum 0

while {[gets $file x] != -1} {
  # if there line has "pattern, then simply print the current sum, then resets it to zero
  if {[regexp pattern $x]} {
    puts $sum
    set sum 0
  } elseif {[regexp {start ([0-9]+)} $x - number]} {
    # if the line matches 'start' followed by <space> and a number, save that number and add it to the sum
    # also, I prefer using incr here than expr. If you do want to use expr, brace your expression [expr {$sum+$ind}]
    incr sum $number
  }
}

# puts the sum
puts $sum