Tcl string processing
last modified November 24, 2026 Tcl 8.6
Tcl was built for gluing programs together, so most of its data arrives as text: log lines, configuration values, CSV exports and command output. The string commands are the ones a Tcl programmer uses every day. They never modify a value in place; each one returns a new string.
This article follows a realistic path from a single line to a small report: splitting and joining, trimming, mapping characters, changing case, counting words, extracting fields and formatting columns. The string command page documents every subcommand, and the split and join pages cover the two list converters used throughout.
Splitting and joining
split cuts a string at every occurrence of a separator and returns
a list; join does the reverse, gluing list elements with a
separator. With no separator argument, split uses a single space
and keeps empty elements, which matters for text with repeated spaces.
set path "usr/local/share/tcl"
set parts [split $path /]
puts "parts: $parts"
puts "count: [llength $parts]"
puts "parent: [join [lrange $parts 0 2] /]"
puts "csv: [join {a b c} ,]"
puts "lines:"
puts [join {one two three} \n]
The path is cut at each slash into four elements. lrange keeps the
first three and join puts the slashes back, a common way to walk a
path without the file command. The last line joins with a newline,
so a list becomes three output lines. split always returns a list,
even when only one element results.
$ tclsh split_join.tcl parts: usr local share tcl count: 4 parent: usr/local/share csv: a,b,c lines: one two three
Trimming
Whitespace at the edges of a line breaks comparisons and column alignment.
string trim removes leading and trailing characters from a set,
whitespace by default; trimleft and trimright remove
from one side only. The set is a bag of characters, not a prefix.
set raw " 2026-11-24 WARN disk usage 75% \n...retry later...\n\tindented line\t\n"
foreach line [split $raw \n] {
set cleaned [string trim $line]
if {$cleaned eq ""} {
continue
}
puts "text: |$cleaned|"
puts "dots: |[string trim $cleaned .]|"
}
set banner "*** Tcl string processing ***"
puts "banner: [string trim $banner *]"
puts "code: [string trimleft 000042 0]"
puts "padded: [string trimright {value }]|"
Each log line loses its surrounding spaces and tabs, and a line made only of whitespace disappears after the empty test. The dots line shows that the character set works anywhere at the edges: the three dots on each side of "retry later" are removed, while dots inside are kept. The last lines strip asterisks from a banner and leading zeros from a number, a small trick that avoids arithmetic.
$ tclsh trimming.tcl text: |2026-11-24 WARN disk usage 75%| dots: |2026-11-24 WARN disk usage 75%| text: |...retry later...| dots: |retry later| text: |indented line| dots: |indented line| banner: Tcl string processing code: 42 padded: value|
Mapping characters
string map takes a list of key and value pairs and replaces every
occurrence of each key. It scans the target once, left to right, so a
replacement is never scanned again; the longer keys should come first when one
key is a prefix of another. A dictionary is a convenient way to hold the pairs.
set template "Hello %NAME%, your order of %TOTAL% is ready."
set values [dict create %NAME% Jane %TOTAL% {$42.00}]
puts [string map $values $template]
set path {/home/jano/My Documents/notes.txt}
puts [string map {{ } _} $path]
puts [string map {a b b a} "abba"]
puts [string map {ab x} "abab"]
The first call fills a template from a dictionary, which keeps the substitution
data separate from the message. The second turns spaces in a path into
underscores. The last two lines show the single-pass rule: swapping
a and b produces a real swap instead of an endless
chain, and ab is replaced as a unit before the shorter keys can see
it.
$ tclsh mapping.tcl Hello Jane, your order of $42.00 is ready. /home/jano/My_Documents/notes.txt baab xx
Changing case
string toupper, tolower and totitle
change case without touching the original. totitle upper-cases the
first character and lower-cases the rest of the whole string, so title-casing a
sentence needs a loop over its words.
set title "the tcl scripting language"
puts [string totitle $title]
puts [string toupper $title]
puts [string tolower "MiXeD Case"]
proc titlecase {text} {
set words {}
foreach word [split $text] {
lappend words [string totitle $word]
}
return [join $words { }]
}
puts [titlecase "CONFIGURATION file FOR the server"]
The first three calls are direct. The procedure splits its argument, applies
totitle to each word and joins the result, which turns a shouted
configuration key into a readable heading. Splitting on whitespace keeps the
problem simple; punctuation attached to a word stays in place.
$ tclsh case.tcl The tcl scripting language THE TCL SCRIPTING LANGUAGE mixed case Configuration File For The Server
Counting words
A word count needs two steps: split the text into words and discard the empty elements that repeated spaces produce. From there, counting occurrences and finding the longest word are simple loops over the list.
set text "the quick brown fox jumps over the lazy dog the end"
set words {}
foreach word [split $text] {
if {$word ne ""} {
lappend words $word
}
}
set longest ""
foreach word $words {
if {[string length $word] > [string length $longest]} {
set longest $word
}
}
set hits 0
foreach word $words {
if {[string equal -nocase $word the]} {
incr hits
}
}
puts "words: [llength $words]"
puts "unique: [llength [lsort -unique $words]]"
puts "longest: $longest ([string length $longest] letters)"
puts "the: $hits times"
The text yields eleven words, nine of them distinct. The longest-word loop keeps
the first word of the maximum length, so ties go to the word that appears
earlier. string equal -nocase counts "the" regardless of case, and
lsort -unique produces a sorted list without duplicates; the
lsort page shows the other ordering options.
$ tclsh words.tcl words: 11 unique: 9 longest: quick (5 letters) the: 3 times
Extracting CSV-like fields
Splitting on newlines and then on commas turns a small CSV export into records. The header line supplies the keys, and each data line is paired with them in order. Trimming every field removes the spaces that often follow a comma.
set data "name,role,city\nJane,Developer,Bratislava\nMarek, Designer ,Kosice\nPeter,,Brno"
set lines [split [string trim $data] \n]
set header [split [lindex $lines 0] ,]
foreach line [lrange $lines 1 end] {
set fields [split $line ,]
set record {}
foreach key $header value $fields {
lappend record [string trim $key] [string trim $value]
}
puts $record
}
puts "header fields: [llength $header]"
puts "data rows: [expr {[llength $lines] - 1}]"
The inner foreach walks two lists at once, one key and one value per
iteration, so the record always matches the header. The spaces around "Designer"
are trimmed, and the missing city becomes an empty element that prints as
{}. This parser is deliberately simple:
commas inside quoted fields need the csv package from Tcllib or the
regular expressions described on the regexp page.
$ tclsh csv.tcl
name Jane role Developer city Bratislava
name Marek role Designer city Kosice
name Peter role {} city Brno
header fields: 3
data rows: 3
Fixed-width columns
format is the tool for tabular text. A minus sign left-aligns a
field, a number sets its width, and a precision such as .2f fixes
the decimals. Numeric fields are right-aligned by default, which lines up the
decimal points.
set rows {
{SSD 512 89.90}
{RAM 16 45.50}
{CPU 8 320.00}
}
puts [format "%-8s %5s %10s" Item Qty Price]
puts [string repeat - 25]
foreach row $rows {
set item [lindex $row 0]
set qty [lindex $row 1]
set price [lindex $row 2]
puts [format "%-8s %5d %10.2f" $item $qty $price]
}
puts [string repeat - 25]
puts [format "%-8s %5s %10.2f" Total {} 455.40]
The header and the rule use the same widths as the rows, so the table stays
aligned without tabs. %5d pads the quantity and
%10.2f reserves ten characters for the price. The total row passes
an empty string for the quantity, which leaves that column blank while the price
keeps its column; a tab character would have broken the alignment.
$ tclsh columns.tcl Item Qty Price ------------------------- SSD 512 89.90 RAM 16 45.50 CPU 8 320.00 ------------------------- Total 455.40
A small report formatter
The last program combines the pieces: it measures each column from the data, builds a format string once, and prints the rows, a rule and a total. Column widths are computed rather than hard-coded, so a longer name widens the table.
set head {Name Role City Salary}
set people {
{Jane Developer Bratislava 3200}
{Marek Designer Kosice 2800}
{Lucia Manager Zilina 4100}
{Peter Tester Brno 2600}
}
set widths {}
foreach h [lrange $head 0 2] {
lappend widths [string length $h]
}
foreach person $people {
for {set i 0} {$i < 3} {incr i} {
set len [string length [lindex $person $i]]
if {$len > [lindex $widths $i]} {
lset widths $i $len
}
}
}
set fmt {}
foreach w $widths {
append fmt "%-${w}s "
}
append fmt "%6s"
puts [format $fmt [lindex $head 0] [lindex $head 1] [lindex $head 2] Salary]
set total 0
foreach person $people {
set salary [lindex $person 3]
incr total $salary
puts [format $fmt [lindex $person 0] [lindex $person 1] \
[lindex $person 2] $salary]
}
set width [string length [format $fmt a b c d]]
puts [string repeat - $width]
puts [format "%-*s%6d" [expr {$width - 6}] "[llength $people] people" $total]
The first loop seeds the widths from the header and then stretches them to fit
the longest value in each of the first three columns. The format string is
assembled with append, using %-Ns for text and a fixed
%6s for the salary. The total is accumulated with
incr while the rows print, and %-*s lets the summary
line take the width computed at run time. The
format page documents the * width.
$ tclsh report.tcl Name Role City Salary Jane Developer Bratislava 3200 Marek Designer Kosice 2800 Lucia Manager Zilina 4100 Peter Tester Brno 2600 ------------------------------------ 4 people 12700
Source
The Tcl 8.6 manual lists every string subcommand, the two list converters and
the conversions accepted by format. Those four pages cover
everything used above.
This article moved from one line of text to a formatted report: split and join, trim, map, change case, count, parse and align. Continue with Tcl dictionaries to see how the parsed fields can be kept as keyed records instead of positional lists.
Author
List all Tcl Tutorials.