-1

I used the tail command to capture the name from a file name before the ".". However, some of my files has name that looks like that (ie: abc.txt.gz). I only want abc and not abc.txt. Please advise.

Current Output


main_name = abc.txt

What I want for final output:


main_name = abc


My script is as below:

foreach xxx $filename {
      puts "main_name = [file rootname [file tail $xxx]]"
}
```````


Kimi
  • 43
  • 1
  • 7

2 Answers2

2

Repeatedly running the file rootname command will remove an extension on every iteration. So by continuing that until the output is the same as the input, you know all extensions have been removed:

foreach name [glob *] {
    set tail [file tail $name]
    set root [file rootname $tail]
    while {$root ne $tail} {
        set tail $root
        set root [file rootname $tail]
    }
    puts "main name = $root"
}
Schelte Bron
  • 4,113
  • 1
  • 7
  • 13
1

A different approach: since the "." is not platform specific:

foreach name [glob *] {
    set tail [file tail $name]
    set dotIdx [string first "." $tail]
    if {$dotIdx > -1} {
        set tail [string range $tail 0 $idx-1]
    }
    puts "main name = $tail"
}
glenn jackman
  • 238,783
  • 38
  • 220
  • 352