Warm tip: This article is reproduced from serverfault.com, please click

TCL list foreach

发布于 2020-12-05 22:37:03

I have the following code: I want to add in the foreach loop to put out the name of the file too.

set outfile [open "out.tcl" w]
set allfiles "[glob /a/b/c/*.txt]"

   foreach files $allfiles {
           puts $outfile "{$files}"
   }

close $outfile

CURRENT OUTFILE WITH THE ABOVE CODE


/a/b/c/123_abc.txt
/a/b/c/2_34cbd.txt
/a/b/c/45_6def.txt
/a/b/c/ABC_2CD.txt
/a/b/c/2BC_AB2.txt
********

WHAT I WANTED AS MY FINAL OUTFILE


/a/b/c/123_abc.txt
123_abc
/a/b/c/2_34cbd.txt
2_34cbd
/a/b/c/45_6def.txt
45_6def
/a/b/c/ABC_2CD.txt
ABC_2CD
/a/b/c/2BC_AB2.txt
2BC_AB2
Questioner
Kimi
Viewed
0
Shawn 2020-12-06 07:07:21

You can get just the filename without leading path or file extension by combining file tail (which removes the leading path) and file rootname (Which removes the extension):

% set files /a/b/c/123_abc.txt
/a/b/c/123_abc.txt
% file tail $files
123_abc.txt
% file rootname $files
/a/b/c/123_abc
% file rootname [file tail $files]
123_abc

So...

set allfiles [glob /a/b/c/*.txt] ;# No quotes needed
foreach files $allfiles {
    puts $outfile $files
    puts $outfile [file rootname [file tail $files]]
}