Saturday, November 02, 2024

Remove Stray Repeated Spaces from a String

 

 

 

#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"

package require -exact Gnocl 3.24

set str "\tAbc  def  ghi   klm    a. \tYes!   "

## reduce multiple spaces within a string but retain \t, trim all external spaces.
# args: str        string to modify
# returns:        updated string
#
proc removeSpaces { str } {
    while 1 {
        if { [string first "  " $str] == -1 } { break }
        set str [string map [list "  " " "] $str]
    }
    return [string trim $str " "]
}

puts >[removeSpaces $str]<

No comments: