Ramesh
Ramesh

Reputation: 5

finding a particular extension files from a directory and printing last 5 according to modified date in TCL

  1. I have a directory in which there are some files of particular extension along with other
    files.

  2. I need the last five files according to their modified date of that particular extension.

  3. If there are more than 5 of that kind, then print only last five and if less than 5 of
    that kind, print all.

Could you please help me in writing this tcl code?

Example 1:

Since there are less than 5 .abc files in this example, we need to collect all in reverse order like last modified date first:

directory: TESTCASE

Files :

- apple_12.abc_no
- banana.abc
- dog.xyz
- place.txt
- sofa_1_2_12.abc
- hello.org

Output:

- sofa_1_2_12.abc
- banana.abc
- apple_12.abc_no

Example 2:

Since there are more than 5 .abc files in this example, we need to last five in reverse order like last modified date first:

Files:

- apple_12.abc_no
- banana.abc
- dog.xyz
- place.txt
- sofa_1_2_12.abc
- hello.org
- world.abc
- stack_133_gre.abc
- potato.txt
- onsite_all.abc
- list.abc

Output :

- list.abc
- onsite_all.abc
- stack_133_gre.abc
- world.abc
- sofa_1_2_12.abc

I tried finding .abc files from the directory TESTCASE by glob command:

set PWD $pwd
set files [glob -tails -directories $PWD/$TESTCASE/*.abc*]
puts $files

but how to tail last five or less, is where I got stuck. We try tail -f filename in unix. is there any way in tcl to do that?

Upvotes: 1

Views: 299

Answers (1)

Jerry
Jerry

Reputation: 71568

There are some issues with your current code. Try this:

# Proc to get latest 5 modified files
proc get_latest {pwd files} {

    # Container for these files
    set newList [list]

    # Loop through each files and get the modified date
    foreach f $files {
        lappend newList [list $f [file mtime $pwd/TESTCASE/$f]]
    }

    # Sort the list on date, putting latest first
    set newList [lsort -decreasing -index 1 $newList]

    # Return top 5
    return [lrange $newList 0 5]
}

# Get path of script
set PWD [pwd]

# Get files with extension
set files_with_ext [glob -tails -directory $PWD/TESTCASE *.abc*]

# Get top 5 files
set top_five [get_latest $PWD $files_with_ext]

# Finally print the file names, removing the introduced timestamps.
foreach f $top_five {
    puts [lindex $f 0]
}

Upvotes: 1

Related Questions