从一个段落中仅获取 tcl/tk 中的前两行

From a paragraph get only first two lines in tcl/tk

作为参考,这是该段落的样子。

{180319 arun S B} first set of chars. first chars.
{180316 yyay S B} second set of chars. second line.
{180314 ramaw S B} third line. third line. third line.
{180309 jfds S B} fouth line
{180221 shrbsd S B} fifth line.fith line part 2.
{180214 shrbs S B} sixth line.

在此我需要提取前两行。喜欢

{180319 arun S B} first set of chars. first chars.
{180316 yyay S B} second set of chars. second line.

我不知道如何在 tcl 中执行此操作。你能建议我这样做吗?虽然我是 tcl 的新手,但我已经在网上冲浪了很多小时,所以很难理解我。谢谢

有几种方法可以做到这一点:

  1. 将段落拆分成行并连接前两行:

    set lines [split $para \n]
    set first2 [lrange $lines 0 1]
    set wanted [join $first2 \n]
    # or
    set wanted [join [lrange [split $para \n] 0 1] \n]
    
  2. 找到第 2 个换行符的位置,并取出从段落开头到该位置的字符

    set firstnewline [string first \n $para]
    set secondnewline [string first \n $para $firstnewline+1]
    set wanted [string range $para 0 $secondnewline-1]
    

    您还可以通过

    获得第二个换行符索引
    set secondnewline [lindex [regexp -all -inline -indices \n $para] 1 0]
    

Tcl 命令记录在此处:https://tcl.tk/man/tcl8.6/TclCmd/contents.htm

工作的 TCL 代码如下:

   set file [open c:/filename.txt ]
     set file_device [read  $file]
     set data [split $file_device "\n"]

        for {set count 0} {$count < 2} {incr count} {
        
        puts $data
        
        # for every iterartion one line will be printed.
     # split /n is use for getting the end of each line.
        # open command open the file at given path. 
        # read command is use to read the open file.
     }
     close $file
     break
       
      

这肯定有效。