如何使用split与最后一个字符读取tcl中的字符串?

时间:2015-07-28 09:27:24

标签: tcl

我正在尝试阅读以下文字,然后打印每个字符串;

0:1:2:3;
1:2:0;
10:13:15;

我写了以下代码

foreach {line} [split [read $lFile] \n] {
   lassign [split $line ;] a
   puts $a
}

但是输出是相同的字符串。我之前想要字符串;

3 个答案:

答案 0 :(得分:2)

在Tcl中,分号标记命令行的结尾,因此,您实际上正在执行split $line而不是split $line ;。您必须引用;才能使其正常工作:

foreach {line} [split [read $lFile] \n] {
   lassign [split $line ";"] a
   puts $a
}

或使用大括号:

foreach {line} [split [read $lFile] \n] {
   lassign [split $line {;}] a
   puts $a
}

答案 1 :(得分:1)

您也可以使用

set a [regsub {;.*} $a ""]

或者,假设分号后面没有文字

set a [string trimright $a ";"]

答案 2 :(得分:0)

输出是相同的字符串,因为foreach中有错误(正如here解释的那样)。但是,您不必使用foreach。您可以使用while循环逐行读取文件。

set file [open lFile.txt r];

while {![eof $file]} {
    gets $file line;
    lassign [split $line ";"] splittedFile;
    puts stdout $splittedFile;
}

或换句话说,只要文件尚未到达其末尾(![eof $file]),就拆分文件并将其打印到标准输出。