我正在尝试阅读以下文字,然后打印每个字符串;
0:1:2:3;
1:2:0;
10:13:15;
我写了以下代码
foreach {line} [split [read $lFile] \n] {
lassign [split $line ;] a
puts $a
}
但是输出是相同的字符串。我之前想要字符串;
答案 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]
),就拆分文件并将其打印到标准输出。