如何从tcl中的文件中获取两个字符串之间的数据?

如何从tcl中的文件中获取两个字符串之间的数据?,tcl,Tcl,在TCL脚本中: 我有一个文件,我知道如何搜索字符串,但如何在找到字符串时获取行号。如果可能,请回答我 或 在上面的程序中,我得到的输出是找到的字符串。如果我给出的字符串不是这个文件中的字符串,我得到的字符串是找不到的。行的概念只是一种约定,我们将从文件中获得的数据流分层。所以,如果你想处理行号,你必须自己计算。获取命令documnetion包含以下示例: set chan [open "some.file.txt"] set lineNumber 0 while {[gets $chan li

在TCL脚本中: 我有一个文件,我知道如何搜索字符串,但如何在找到字符串时获取行号。如果可能,请回答我


在上面的程序中,我得到的输出是找到的字符串。如果我给出的字符串不是这个文件中的字符串,我得到的字符串是找不到的。

行的概念只是一种约定,我们将从文件中获得的数据流分层。所以,如果你想处理行号,你必须自己计算。
获取
命令documnetion包含以下示例:

set chan [open "some.file.txt"]
set lineNumber 0
while {[gets $chan line] >= 0} {
    puts "[incr lineNumber]: $line"
}
close $chan
因此,您只需将puts语句替换为您的代码,以查找您想要查找的文本模式,当您找到它时,
$line
的值将为您提供行号

要复制位于其他两行之间的文本,我将使用如下内容

set chan [open "some.file.txt"]
set out [open "output.file.txt" "w"]
set lineNumber 0
# Read until we find the start pattern
while {[gets $chan line] >= 0} {
    incr lineNumber
    if { [string match "startpattern" $line]} {
        # Now read until we find the stop pattern
        while {[gets $chan line] >= 0} {
            incr lineNumber
            if { [string match "stoppattern" $line] } {
                close $out
                break
            } else {
                puts $out $line
            }
        }
    }
}
close $chan

最简单的方法是使用
fileutil::grep
命令:

package require fileutil

# Search for ipsum from test.txt
foreach match [fileutil::grep "ipsum" test.txt] {
    # Each match is file:line:text
    set match      [split $match ":"]
    set lineNumber [lindex $match 1]
    set lineText   [lindex $match 2]

    # do something with lineNumber and lineText
    puts "$lineNumber - $lineText"
}
更新 我意识到,如果该行包含冒号,则
lineText
在第三个冒号处被截断。因此,不是:

    set lineText   [lindex $match 2]
我们需要:

    set lineText   [join [lrange $match 2 end] ":"]

到目前为止你试过什么?如果您向我们展示您所做的,您会得到更好的响应。我尝试使用regexp命令。我可以找到字符串,但如何从文件中找到行号?感谢您的帮助,但它仅适用于startin字符串。在找到第一个字符串之后,它将复制所有文件。那么,您的数据文件是什么样子的?起始和终止字符串是什么?您是否已检查您是否正确检测到停止字符串?您可以发布一个短数据文件,大约6行,但不起作用吗?您好,谢谢您的解决方案。我正在获取两个字符串之间的数据,但它显示的错误消息是C:\Users\atangutu\Desktop\anwesh>Tlsh task1.tcl在执行“put$out$line”(“while”body line 11)时找不到名为“file1276940”的频道从“while{[gets$chan line]>=0}{[string match”S1应用程序协议“$line]”中调用{#现在读取,直到找到s..”(文件“task1.tcl”第5行)C:\Users\atangutu\Desktop\anwesh>
    set lineText   [lindex $match 2]
    set lineText   [join [lrange $match 2 end] ":"]