从一个文件中提取感兴趣的行并将其输出到另一个文件

时间:2011-04-07 05:23:31

标签: tcl

我有一个文件如下

$ ###########################################################

$ # text           : text

$ # text            : text

$ # text   : text

$ # text   : text

$ # text : text

$ ###########################################################

.some text

$$.some text 

$ ###########################################################

$ # text           : text

$ # text           : text

$ #text            : text

$ # text           : text

$ # text           : text

$ ###########################################################


$# some text 

要提取的行是

Mg1.qna some text

Mg1.qpa text

这两行将被写入另一个文件.........

我有一些逻辑,但那是自然的标志.......尝试2给出想法,如果有的话

3 个答案:

答案 0 :(得分:3)

检测是否要忽略某一行的最简单方法是使用string match,尤其是涉及文字字符$时(string match并不特别)。例如:

set f [open $filename]
while {[gets $f line] >= 0} {
    if {[string match "$$*" $line] || [string match "$ #*" $line]} {
        # ignore by just going straight to the next loop iteration
        continue
    }
    # Do the rest of your processing here...
}
close $f

请注意,虽然$是字符串中的元字符,但如果后面没有字母,数字,冒号或括号,则它会替换为自身。如上所述,周期,星号和空格都很好。 (否则,您需要在每个美元符号前加上反斜杠\。)

答案 1 :(得分:0)

这是我的解决方案,它使用Tclx包中的for_file来读取文件。您不必使用它,但我只是想显示一种替代方法来逐行读取文件。每个匹配的行都将写入输出文件:

package require Tclx

set inputFilename [lindex $argv 0]
set outputFilename [lindex $argv 1]
set outputChannel [open $outputFilename w]

for_file line $inputFilename {
    # Only select those lines that does not start with '$' or '.'
    if [regexp {^[^\$\.]} $line] {
        puts $outputChannel $line
    }
}

close $outputChannel

答案 2 :(得分:0)

在评论中将drysdam提到的解决方案扩展到问题

在shell上,您可以使用以下

grep ^ Mg file1> file2

也可以从TCL脚本执行相同的命令。

eval exec“grep ^ Mg file1> file2”

行动中:

==> tclsh的 %cat d1 MG1 镁 BG %

%eval exec“grep ^ Mg d1> d2”<<<<<<<<<< TCL的解决方案

%cat d2 MG1 MG2

相关问题