如何解决使用'sed'查找和替换与号&的问题
特殊情况下,与号(&)和GROUP BY USRegion,ZipCode,State,StateCd,City,ResellerName,LastName+','+FirstName,IllnessName,DimProduct.ProductKey,OrderDate
想用sed
中的&
字符串替换字符串
bash
预期输出为:INPUT:
var1=''XXX&XXX'
Input : sed -i 's/WW/$var1/g' test
Output:
$cat test
XXXWWXXX
PS:字符串是动态的,所以在这里我不想用转义符修改变量, 外壳?
解决方法
像这样使用它:
var1='XXX&XXX'
# Use double quotes in sed
# Note: & is escaped
sed "s/WW/${var1//&/\\&}/g" <<< '123 WW foo WW xyz.'
输出:
123 XXX&XXX foo XXX&XXX xyz.
,
由于您说过i don't want to modify variable with / (sic) escape character
-这将对您要匹配的现有文本(WW
和替换文本(XXX&XXX
)使用文字字符串匹配,这是避免转义的方法其中任何一个字符:
var1='XXX&XXX'
old='WW' new="$var1" awk '
BEGIN {
old = ENVIRON["old"]
new = ENVIRON["new"]
lgth = length(old)
}
{
head = ""
tail = $0
while ( s = index(tail,old) ) {
head = head substr(tail,1,s-1) new
tail = substr(tail,s+lgth)
}
$0 = head tail
print
}
' test
有关我如何使用shell和awk变量,请参见How do I use shell variables in an awk script?。
您无法对sed进行上述操作,因为sed无法理解文字字符串,因此,如果您想使用sed,请参阅Is it possible to escape regex metacharacters reliably with sed。
,发现解决方案是,在最近的shell中,可以这样做,
需要放置此//&/\\&
静态字符集来解决sed
的&符号问题
s1="XXX&XXX"
sed "s/ww/${s1//&/\\&}/g" <<< 'this is ww'
this is XXX&XXX
其他情况,
s2="&xx&xx&x&"
sed "s/ww/${s2//&/\\&}/g" <<< 'this is ww'
this is &xx&xx&x&
快速搜索发现了罪魁祸首;
The REPLACEMENT can contain \N (N being a number from 1 to 9,inclusive)
references,which refer to the portion of the match which is contained
between the Nth \( and its matching \). Also,the REPLACEMENT can contain
unescaped & characters which reference the whole matched portion of the pattern space
让我们尝试 awk
URI='https://user:pass@example.com/?num=42&type=magic'
$ echo 'my_link = %link%' | awk "{ gsub(/%link%/,\"$URI\"); print }"
my_link = https://user:pass@example.com/?num=42%link%type=magic
查找有关https://www.gnu.org/software/sed/manual/sed.html
的更多信息干杯!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。