Question

I am trying to read a file line by line and wanted to remove the white space characters if any using TCL.

I am using trim command to remove the spaces, but it is not getting trimmed.

details.config (Input file)

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]<"

Output

-->  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

What went wrong here?

Était-ce utile?

La solution

To remove all whitespace you don't use trim (only does the start and end). Use this

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

instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top