Reputation: 23
I am trying to use string map function in my script. I have a attribute whose value looks like below:
{{1234||}{2345||}}
I want to replace all the opening curly bracket with blank char and ||}
with
comma ,
. How can i use map function?
How to escape the braces in above?
Upvotes: 0
Views: 529
Reputation: 137587
You can always use list
(or other list operations) to build the mapping term. This is a great time to work with an interactive terminal.
% list "{" "" "||}" ","
\{ {} ||\} ,
Now we know what the literal list looks like, we can use it in the script:
set s "{{1234||}{2345||}}"
set result [string map {\{ {} ||\} ,} $s]
puts "“$s” --> “$result”"
# “{{1234||}{2345||}}” --> “1234,2345,}”
Of course, it might be that you were telling us the quoted input value:
set s {{1234||}{2345||}}
set result [string map {\{ {} ||\} ,} $s]
puts "“$s” --> “$result”"
# “{1234||}{2345||}” --> “1234,2345,”
(Unicode quotes are useful for delimiting output strings when testing, as they're not mistaken for input values.)
Upvotes: 0
Reputation: 71548
The manual should be clear enough, but just in case...
set s "{{1234||}{2345||}}"
set result [string map {"{" "" "||}" ","} $s]
puts $result
# 1234,2345,}
string map
takes a list containing pair of strings. In each pair in that list going from left to right, the first one will get replaced with the second one.
Therefore in the above, first {
will be replaced with blank, and when this is done, ||}
will be replaced with ,
. I'm using quotes because braces are used for quoting in Tcl and it might not always work as you want it to if you are not too used to how the quoting mechanism works in Tcl.
Though I'm not too sure if the above is the result you are looking for? You can use string trimright
if you want to remove the extra ,}
which will remove all trailing characters that are ,
and }
:
string trimright $result ",}"
# 1234,2345
Also sidenote, you escape characters in Tcl using a backslash (\
).
Upvotes: 2
Reputation: 151
The best solution is to use regsub
if you want to replace parts of a string:
set str {{1234||}{2345||}}
regsub -all {\{} $str "" str
regsub -all {\|\|\}} $str "," str
puts $str
Upvotes: 0