harishli2020
harishli2020

Reputation: 315

How to replace backward slash(\) with forward slash(/) in TCL script

I'm writing a TCL script and I would like to replace \ with /.

#File directory
set fDir "U:\scripts"
#Replacment of \ with / in the directory path using regular expression
regsub -all {\\} $fDir {/} fDir
tk_messageBox -message $fDir

I'm getting output as: U:scripts

I would like have the output as: U:/scripts

Upvotes: 1

Views: 4606

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13252

If you use a single backslash, the interpreter tries to construct an escape sequence from it. When it fails, it just strips the backslash:

% set fDir "U:\scripts"
U:scripts

To get a string with a backslash in it, you need to either brace the string or escape the backslash:

% set fDir {U:\scripts}
U:\scripts
% set fDir U:\\scripts
U:\scripts

Then you can use your regsub invocation to change the backslashes to slashes. If you don’t feel it’s necessary to go the long route through a regular expression, you can use the dedicated command for it:

% set fDir [file normalize $fDir]

Documentation:

file

Summary of Tcl language syntax

Upvotes: 4

devil_coder
devil_coder

Reputation: 1135

Try

#File directory
set fDir "U:\\scripts"
#Replacment of \ with / in the directory path using regular expression
regsub -all {\\} $fDir / fDir
puts $fDir

I tested on online editor and it worked

Result is

U:/scripts

Upvotes: 0

Related Questions