在tcl脚本中使用sed替换字符串 - 字符串包含圆括号

问题描述 投票:0回答:4

我想在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中处理圆括号和&符号?

regex string sed tcl substitution
4个回答
1
投票

您是否考虑过使用Tcl进行此就地转换,例如通过其[regsub]命令:

set x [regsub {(\([^)]*\))} $x ch0_prbs_match_int]
set x [regsub {(\([^)]*\))} $x ch1_prbs_match_int]

只修复线(唯一)

这假设变量x保存文件的内容,并且可以通过注意匹配的括号对来唯一地标识要替换的线元素。


1
投票

如果您在变量中包含文件内容(或文件的一行),则可以使用string map命令将一个子字符串替换为其他文本。


1
投票

我想通了 - 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

0
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.