查找一个文件中开头的行特定的单词
问题描述:
我想获得的行号在我的文件与特定的单词开始。对于下面的例子,我只想得到数字5,如果我正在寻找绑定。查找一个文件中开头的行特定的单词
module checker_m;
// bind
`include "assertions.v"
endmodule
bind top checker_m checker_inst();
如果你能人建议我一个Tcl的解决方案,这将是最好的 - 我与的Tcl解释器工具的工作。我可以用“exec”调用任何基于Linux的命令。
非常感谢!
答
假设该文件名可变FNM和您要搜索的是变量的候选词列表中,这样的事情应该工作举行:
# Read in all the input data
set fil [open $fnm]
set data [read $fil]
close $fnm
# Check each input line to see whether if the first word appears in the
# candidate list
set lineNo 0
foreach line [split $data \n] {
incr lineNo
set words [split $line " "]
set firstWord [lindex $words 0]
if {[lsearch $candidates $firstWord] >= 0} {
puts stdout "Line $lineNo starts with $firstWord"
}
}
免责声明:我没有实际上测试了这个,所以它可能包含一些愚蠢的错误,但我相信它正确地说明了原则。如果输入的文件是非常大,你可能会更好的阅读它在使用gets
,当你阅读测试线路,时间线,但我肯定不能说(几乎)正确地第一次写出来的。
好运
答
使用gets
A液:
set word bind
set n 0
set f [open file]
while {[gets $f line] >= 0} {
incr n
if {[string match $word* $line]} {
puts "Line $n"
}
}
close $f
使用fileutil
包类似的解决方案。
package require fileutil
set word bind
set n 0
::fileutil::foreachLine line file {
incr n
if {[string match $word* $line]} {
puts "Line $n"
}
}
一个班轮溶液:
lindex [split [lindex [::fileutil::grep ^$word\\M file] 0] :] 1
文档: >= (operator), close, fileutil (package), gets, if, incr, lindex, open, package, puts, set, split, string, while, Syntax of Tcl regular expressions
Tcl的字符串匹配的语法:
-
*
的零序列或匹配多个字符 -
?
匹配单个字符 -
[chars]
在由字符(给定组中的单个字符匹配^确实不否定;一系列可以作为A-Z) -
\x
X匹配的字符,即使该字符是特殊(的*?[]\
之一)
答
set lineno [exec grep -n {^bind\>} $filename | cut -d: -f1]
谢谢!这工作!你认为什么是一个大文件?我的文件少于2k行。 – user3518939
抱歉,延迟响应。我的解决方案使用'read'的“问题”是您必须将整个文件存储在进程的内存空间中。用现代计算机系统,我不会担心,直到它达到兆字节或更多;这应该允许你处理几万行的文件,所以你2000行的文件不应该成为问题。 – nurdglaw