.
.
名称
split - 将字符串分解成Tcl列表
语法
split string ?splitChars?
描述
根据splitChars变元中的字符分解string,返回一个列表。每个列表元素由string中在splitChars字符之间的字符组成,如果string含有两个连续的字符与splitChars中的字符相同或者第一或最后一个字符为splitChars中的字符就返回一个空列表元素,如果splitChars是一个空字符串那么string的每一个字符作为单独的元素组成列表,缺省splitChars为空格符。
示例
使用给定的字符分解一个网络用户组名:
split "comp.lang.tcl.announce" .
→ comp lang tcl announce
split命令使用splitChars所有的字符作为分解字符,例如分解字符为"ab",那么作为分解的字符不是字符串"ab",而是a和b都作为分解字符,如下:
split "alpha beta gamma" "temp"
→ al {ha b} {} {a ga} {} a
从一个字符串中释放列表字符:
split "Example with {unbalanced brace character"
→ Example with /{unbalanced brace character
分解一个字符串为单独的字符列表:
split "Hello world" {}
→ H e l l o { } w o r l d
分解记录文件
分析一个Unix的/etc/passwd文件,文件内容由一行一行组成,使用换行符来分解文件。
## Read the file
set fid [open /etc/passwd]
set content [read $fid]
close $fid
## Split into records on newlines
set records [split $content "/n"]
## Iterate over the records
foreach rec $records {
## Split into fields on colons
set fields [split $rec ":"]
## Assign fields to variables and print some out...
lassign $fields /
userName password uid grp longName homeDir shell
puts "$longName uses [file tail $shell] for a login shell"
}