Search code examples
stringtcltk-toolkittrim

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


For reference this is how the paragraph looks like.

{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.

In this I need to extract first two lines. like

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

I don't have any idea how to do this in tcl. can you please suggest me to do this. I have surfed many hours in online though I'm new to tcl so it is hard to understand me. Thanks


Solution

  • There's a couple of ways to do this:

    1. split the paragraph into lines and join the first 2 lines:

      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. find the position of the 2nd newline and take the characters from the start of the paragraph up to that position

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

      You can also get the 2nd newline index with

      set secondnewline [lindex [regexp -all -inline -indices \n $para] 1 0]
      

    Tcl commands are documented here: https://tcl.tk/man/tcl8.6/TclCmd/contents.htm