Main Content

Tcl - apparently odd behaviour of string trimleft

Archive - Originally posted on "The Horse's Mouth" - 2012-01-13 21:03:36 - Graham Ellis

Question:

Why does this code:

  set dir "D:/JNN/proc/"
  set tempname "D:/JNN/proc/Doc-99887767.dat"
  set cname [string trimleft $tempname $dir]
  puts $cname

report
  -99887767.dat

but this code:

  set dir "D:/JNN/proc/"
  set tempname "D:/JNN/proc/Foc-99887767.dat"
  set cname [string trimleft $tempname $dir]
  puts $cname

report
  Foc-99887767.dat

Answer

The second parameter to string trimleft (the one that's in $dir in the example) is treated as a list of individual characters to be removed. And in the first example, the "D" "o" and "c" are stripped off the beginning of the file name because they also occur in the directory name.

Suggestion

If you want to strip the leading directory information off a path and file name, you may find it better to use regsub
  set cname [regsub {.*/} $tempname ""]
the apparently spurious .* meaning we trim to the last / rather than the first.