首页 > 解决方案 > 识别文本文件中的空行并在 tcl 中使用该列表循环

问题描述

我有一个文件,其中包含以下类型的数据

A 1 2 3 
B 2 2 2

c 2 4 5

d 4 5 6

从上面的文件中,我想执行一个循环,例如,

三次迭代,其中第一次迭代将具有 A、B 元素,第二次迭代具有 c 元素,第三次迭代具有 d。这样我的 html 表看起来像

Week1    |  week2    |   week3
----------------------------
A 1 2 3  |  c 2 4 5 | d 4 5 6
B 2 2 2

我在 SO catch tcl 文件中的多个空行中发现了这一点,但我没有得到我真正想要的。

标签: tcl

解决方案


我建议使用数组:

# Counter
set week 1
# Create file channel
set file [open filename.txt r]

# Read file contents line by line and store the line in the varialbe called $line
while {[gets $file line] != -1} {
    if {$line != ""} {
        # if line not empty, add line to current array with counter $week
        lappend Week($week) $line
    } else {
        # else, increment week number
        incr week
    }
}
# close file channel
close $file
# print Week array
parray Week

# Week(1) = {A 1 2 3} {B 2 2 2}
# Week(2) = {c 2 4 5}
# Week(3) = {d 4 5 6}

ideone演示


推荐阅读