String 使用TCL从文件中读取字符串后从字符串中删除空间

String 使用TCL从文件中读取字符串后从字符串中删除空间,string,file-io,tcl,trim,String,File Io,Tcl,Trim,我试图逐行读取文件,并希望使用TCL删除空白字符(如果有) 我正在使用trim命令删除空格,但它没有被修剪 details.config(输入文件) mystr\u示例.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 ]

我试图逐行读取文件,并希望使用TCL删除空白字符(如果有)

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

details.config(输入文件)

mystr\u示例.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]<"
#/usr/bin/expect
设置配置文件“details.config”
设置文件句柄[打开$config\u文件]
而{[get$file_handle line]!=-1}{
#设置行[string trim$line](我认为这可能是错误的)
#设置行[string trim$line”“](即使我们没有给出第二个参数,
#然后它必须删除空白。对吗?)
#只是把它复制到另一个变量
设置测试$line
#现在,修剪并将其保存到变量“final”
设置最终[字符串修剪$test]
#set final[string trim$test”“]-->也尝试了此操作
放入“->$final”;
}
#下面的例子中,我发现从互联网上这是工作良好。
设置str“你好,世界”

将“original:>$str[string trimleft$str][string trimright$str][string trim$str]放入以删除所有不使用trim的空白(仅开始和结束)。使用此选项

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

相反。

事实上-对于用其他东西替换所有子字符串的这种特殊情况,我建议使用
字符串映射{“”}$test
。编译正则表达式相对较慢。不过这是一次性(每个线程)的开销,所以通常可以忽略不计;
{\s+}
可能更快…而且
\s
通常会删除空白,而字符串映射示例则严格删除空格。
-->  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
regsub -all {\s} $test {} final