开发者

Extracting lines of interest from one file and outputing the same to another file

I have a file as follows

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

$ # text           : text

$ # text            : text

$ # text   : text

$ # text   : text

$ # text : text

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

.some text

$$.some text 

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

$ # text           : te开发者_如何学JAVAxt

$ # text           : text

$ #text            : text

$ # text           : text

$ # text           : text

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


$# some text 

The lines to be extracted are

Mg1.qna some text

Mg1.qpa text

these two lines are to be written to another file .........

I have some logic but thats nat upto the mark....... try 2 give ideas if any


The easiest way to detect if a line is to be ignored is to use string match, especially when the literal character $ is involved (it's not special at all to string match). For example:

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

Note that while $ is a metacharacter inside strings, it substitutes as itself if it is not followed by a letter, number, colon or parenthesis. Periods, asterisks and spaces are fine as used above. (Otherwise, you'd need to put a backslash, \, in front of each dollar symbol.)


Here is my solution, which use for_file from the Tclx package to read the file. You don't have to use it, but I just want to show an alternative method to reading files, line by line. Each matched line will be written to an output 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


Extending the solution mentioned by drysdam in comments to question

On shell you do use the following

grep ^Mg file1 > file2

Same command can be executed from TCL script too.

eval exec "grep ^Mg file1 > file2"

In action:

==>tclsh % cat d1 Mg1 Mg2 Bg %

% eval exec "grep ^Mg d1 > d2" <<<<<<<<< Solution for TCL

% cat d2 Mg1 Mg2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜