DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Shell-to-array

01.17.2007
| 1373 views |
  • submit to reddit
        Demonstration: How to obtain variables / arrays from unix shell

#!/usr/bin/tclsh
# Demonstration: How to obtain variables / arrays from unix shell
#

proc tokenize {buf} {
   set exp {[^ \t]*[ \t]*}
   # use "-indices" if you just care about the indices
   return [regexp -all -inline -- $exp $buf]
}

# get a number from shell
set p [exec ls -1 | grep "" -c ]
puts "Got a number from shell: $p"

set v [exec ls -1]

# the RegExp way: Matches everything from the beginning to the end of a line
set exp {^.*$} 

# create an array of files
set filelist [regexp -line -all -inline -- $exp $v]

# The ancient C-Way would have looked like this:
#for { set i 0} {$i < $p} { incr i } {
#   scan $v "%s%n" file length
#   lappend filelist $file
#   set v [string range $v $length end]
#}
#

# show list
foreach file $filelist  {
   puts $file
}

# and tell me the length
puts [llength $filelist ]