从段落获得的Tcl / Tk只有前两行

问题描述 投票:0回答:2

作为参考,这是一段怎样的模样。

{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,所以很难理解我。谢谢

string tcl tk trim
2个回答
1
投票

有一对夫妇的方式做到这一点:

  1. 分裂成段线和连接第一2行: 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


0
投票

工作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
    			
    		

这将肯定工作。

© www.soinside.com 2019 - 2024. All rights reserved.