Heyya
Heyya

Reputation: 57

How to look for particular lines in a file using Tcl

I have 2 files with similar contents and want to extract certain lines from each file and compare their values. The lines that I am interested in are as an example :

First file :

11 stringABC /dir/path/to/stringABC 
20 stringXYZ /dir/path/stringXYZ 

Second File:

13 stringABC /dir/path/of/secondFile/stringABC
151 stringXYZ /dir/path/stringXYZ
25  stringabc /dir/path/to/stringabc

Once i can recognize such lines in both the files i would compare the paths of stringABC and stringXYZ. Output would show a difference of path for stringABC whereas it matches for stringXYZ and missing entry in first file for stringabc.

i am using regexp to look for patterns that start with some digits followed by some string and then paths to directories.

First :  "{^(\d)*}"
Second: "[a-z]"
Third : "{(^/)}"`

Need to combine all three of these and catch such lines.

Upvotes: -1

Views: 128

Answers (1)

Chris Heithoff
Chris Heithoff

Reputation: 1863

Instead of using regexp, try the scan command:

set line "25  stringabc /dir/path/to/stringabc"
if {[llength $line]==3 && [scan $line "%d %s %s" num str path] == 3} {
    if {[string match /* $path]} {
        # Do something with $num, $str, $path
    }
} else {
    # The line didn't start with an integer followed by two strings
}

Using scan is generally easier to use than regexp but is not as robust in case your possible lines may include something unexpected.

The following regexp will match exactly an integer, followed by an alphanumeric string, and concluding with a path name.

if {[regexp {^(\d+) +(\w+) +([[:alnum:]/]+$)} $l -> num str path] == 1} {
    # This matches.  Do something with $num, $str and $path
}

Upvotes: 0

Related Questions