如何用tcl脚本替换字符串中的特殊字符?

时间:2020-02-18 08:24:16

标签: tcl

在file.txt中

obj = "hi/this/is[1]/script"

将字符串转换为

obj = "hi/this/is\[1]/script"

在tcl中有办法吗?

2 个答案:

答案 0 :(得分:1)

如果要替换所有出现的字符,string map非常适合:

# Careful with the quoting here
set obj [string map [list {[} {\[}] $obj]

如果您只想替换第一个匹配项,regsub是一个更好的工具

set obj [regsub {\[} $obj {\\&}]

&成为匹配的字符串,我们需要注意RE和替换文本中的反斜杠。)

答案 1 :(得分:0)

一种方法是使用string map

% set obj {obj = "hi/this/is[1]/script"}
obj = "hi/this/is[1]/script"
% string map {\[ \\\[} $obj
obj = "hi/this/is\[1]/script"