从文件中完全按照它们出现的方式读取行 [英] Read lines from file exactly as they appear

查看:15
本文介绍了从文件中完全按照它们出现的方式读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个文件,需要找到确切的行 $(eval $(call CreateTest KEYWORD) 以及该行之后的所有内容(因为其余部分都是随机的).这就是我的方式我目前正在尝试找到它,但它总是报告没有找到匹配的内容.

I am reading from a file and need to find the exact line $(eval $(call CreateTest KEYWORD and everything following after the line (as the rest is all random). This is how I am currently trying to find it but it always reports back as nothing found to match.

proc listFromFile {$path1} {
    set find {$(eval $(call CreateTest, KEYWORD}
    upvar path1 path1
    set f [open $path1 r]
    set data [split [string trim [read $f]] \n]
    close $f
#   return [lsearch -all -inline $data *KEYWORD*]
    return [lsearch -exact -all -inline $data $find*]
}

注释掉的行是我可以让它工作的最接近的行,但它会在文件中的任何位置提取带有 KEYWORD 的任何内容.KEYWORD 可能出现在我不想阅读的行中,因此我需要按上述方式拉出确切的行

The commented out line is the closest I can get it to work but it pulls anything with KEYWORD anywhere in the file. the KEYWORD could appear in lines I do not want to read therefore I need to pull the exact line as stated above

编辑我应该提到文件的格式是这样的;

EDIT I should have mentioned that the file is formatted like so;

$(eval $(call CreateTest, KEYWORD ...
$(eval $(call CreateTest, NOT_KEYWORD ...
$(eval $(call CreateTest, KEYWORD ...
$(eval $(call CreateTest, KEYWORD ...
$(eval $(call CreateTest, NOT_KEYWORD ...
$(eval $(call CreateTest, KEYWORD ...

这意味着我只想提取包含确切字符串和关键字的行.但是在我不想显示的内容之间存在界限

which means I only want to pull the lines containing the exact string and the keyword. But there are lines between what I am looking for that I do not want to display

推荐答案

我认为你应该在阅读每一行时应用你的匹配.

I think you should just apply your match to each line as you read them.

proc getMatchingLines {filename match} {
    set result {}
    set f [open $filename r]
    while {[gets $f line] != -1} {
        if {[string match ${find}* $line]} {
            lappend result $line
        }
     }
    close $f
    return $result
}

set find {$(eval $(call CreateTest, KEYWORD}
set matching [getMatchingLines $filename $find]
foreach line $matching {
    # do something with the matching line
}

您可以根据您的应用程序为每个匹配的行建立一个结果列表或立即执行某些操作.主要区别在于 string match 不像正则表达式那样有很多元字符.只有 *? 是特殊的,因此很容易匹配与您的字符串匹配的行,后跟任何内容,即:${find}*.

You could build up a list of results or do something immediately for each matching line as appropriate for your application. The main difference is that string match doesn't have many meta characters unlike regexp. Only * and ? are special so it is simple to match for a line matching your string followed by anything ie: ${find}*.

这篇关于从文件中完全按照它们出现的方式读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆