user2095095
user2095095

Reputation: 31

tcl sort a file

I have a directory which has multiple files by the name *MIS. Now these files contain repeated lines. I need to read all files in the directory named VIA having name *_MIS & update the file after removing the repeated lines(need to do sort -u). Need to use TCL

Upvotes: 0

Views: 5623

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

If you're doing this in pure Tcl, you should split the task into two pieces: a part to sort a file (which will make a nice procedure) and a part that sorts all the relevant files in a directory:

proc sort_file {filename} {
    # Read the file
    set f [open $filename]
    set data [read $f]
    close $f

    # Sort the lines, removing dupes
    set lines [split $data "\n"]
    set sorted_uniques [lsort -unique $lines]
    set data [join $sorted_uniques "\n"]

    # Write the file
    set f [open $filename w]
    puts $f $data
    close $f
}

# Now process all the relevant files; the -directory option is a convenient way
# to specify which directory to do the searching in.
foreach filename [glob -directory VIA *_MIS] {
    sort_file $filename
}

Key parts of the solution: lsort -unique and foreach/glob.

Upvotes: 3

Roman Kaganovich
Roman Kaganovich

Reputation: 658

You can try the following

set dir_path path_to_directory_contains_MIS_files
set files_list [glob -directory $dir_path *_MIS]
foreach mis_file $files_list {
    if {[catch {exec sort -u $mis_file -o $mis_file} result]} {
        puts "ERROR: $result"
    } 
}

Upvotes: 2

Related Questions