使用TCL从文件中读取空格后删除空格

时间:2014-04-22 11:06:50

标签: string file-io tcl trim

我正在尝试逐行读取文件,并希望删除空格字符(如果有的话)使用TCL。

我正在使用trim命令删除空格,但它没有被修剪。

details.config (输入文件)

sys_username = dinesh
sys_password = dinesh
ftp_ip = 0.0.0.0
ftp_username = ftpuser
ftp_password = ftppassword

mystr_example.tcl

#!/usr/bin/expect
set config_file "details.config"

set file_handle [open $config_file]
while {[gets $file_handle line] != -1} {
#set line [ string trim $line ] (I thought this might be wrong)
#set line [ string trim $line " "] (even if we didnt give the 2nd argument, 
# then it has to remove the whitespaces. Correct ? ) 
#Just copying it to another variable
set test $line
#Now, trimming and saving it to variable 'final'
set final [string trim $test]
#set final [string trim $test " "] ---> Tried this too
puts "-->  $final";
}

#Below example, I found from internet which is working fine.
set str "      hello world      "
puts "original: >$str<"
puts "trimmed head: >[string trimleft $str]<"
puts "trimmed tail: >[string trimright $str]<"
puts "trimmed both: >[string trim $str]<"

输出

-->  sys_username = dinesh #Spaces are still there in output
-->  sys_password = dinesh
-->  ftp_ip = 0.0.0.0
-->  ftp_username = ftpuser
-->  ftp_password = ftppassword

original: >      hello world      <
trimmed head: >hello world      <
trimmed tail: >      hello world<
trimmed both: >hello world< #Spaces removed here

这里出了什么问题?

1 个答案:

答案 0 :(得分:2)

要删除所有空格,请不要使用修剪(仅限开始和结束)。使用此

regsub -all {\s} $test {} final

代替。