我想在tcl脚本中使用sed来修改包含字符串的文件(存储在$ file中):
prbs_match_out <=(ch0_prbs_match_dual3_int&ch0_prbs_match_dual2_int&ch0_prbs_match_dual1_int&ch0_prbs_match_int)&(ch1_prbs_match_dual3_int&ch1_prbs_match_dual2_int&ch1_prbs_match_dual1_int&ch1_prbs_match_int);
至
prbs_match_out <= ch0_prbs_match_int&ch1_prbs_match_int;
尝试:
exec /bin/sed -i {s/(ch0_prbs_match_dual3_int & ch0_prbs_match_dual2_int & ch0_prbs_match_dual1_int & ch0_prbs_match_int) & ( ch1_prbs_match_dual3_int & ch1_prbs_match_dual2_int & ch1_prbs_match_dual1_int & ch1_prbs_match_int)/ch0_prbs_match_int & ch1_prbs_match_int/g} $file
上面的sed命令不起作用(获取不正确的替换)。如何在sed中处理圆括号和&符号?
您是否考虑过使用Tcl进行此就地转换,例如通过其[regsub]
命令:
set x [regsub {(\([^)]*\))} $x ch0_prbs_match_int]
set x [regsub {(\([^)]*\))} $x ch1_prbs_match_int]
只修复线(唯一)
这假设变量x
保存文件的内容,并且可以通过注意匹配的括号对来唯一地标识要替换的线元素。
如果您在变量中包含文件内容(或文件的一行),则可以使用string map
命令将一个子字符串替换为其他文本。
我想通了 - tcl的“字符串映射”命令有效。谢谢你的帮助。
package require Tcl 8.5
package require fileutil
# Parameters for the replacement
set from "( ch0_prbs_match_dual3_int & ch0_prbs_match_dual2_int & ch0_prbs_match_dual1_int & ch0_prbs_match_int) & ( ch1_prbs_match_dual3_int & ch1_prbs_match_dual2_int & ch1_prbs_match_dual1_int & ch1_prbs_match_int)"
set to "ch0_prbs_match_int & ch1_prbs_match_int"
# Which file to replace
set checkingFile /proj/dada/test.v
# Make a command fragment that performs the replacement on a supplied string
set replacementCmd [list string map [list $from $to]]
# For single file replacement
fileutil::updateInPlace $checkingFile $replacementCmd
在BRE
(基本正则表达式)中,只有六个字符必须被转义为字面处理:^$.*\[
。
此外,你需要在&
的REPLACEMENT
命令的s
部分中逃避sed
,因为&
具有PATTERN
中匹配部分的特殊含义。
结果,你可以这样说:
#!/usr/bin/tclsh
set file {yourfilename}
exec /bin/sed -i {s/(ch0_prbs_match_dual3_int & ch0_prbs_match_dual2_int & ch0_prbs_match_dual1_int & ch0_prbs_match_int) & ( ch1_prbs_match_dual3_int & ch1_prbs_match_dual2_int & ch1_prbs_match_dual1_int & ch1_prbs_match_int);/ch0_prbs_match_int \& ch1_prbs_match_int;/} $file
它将$file
修改为:
prbs_match_out <= ch0_prbs_match_int & ch1_prbs_match_int;