使用sed用char'X'替换两个字符串之间的所有字符 [英] Substitute all characters between two strings by char 'X' using sed
问题描述
在Bash脚本中,我试图在文件内用'X'替换两个给定字符串之间的字符.我有一堆字符串对,我希望在它们之间用'X'替换字符.
在下面的代码中,在 cpi_list 数组中声明了该对中的 first 字符串.该对中的 second 字符串始终为 %26
或&
或ENDOFLINE
In a Bash script, I am trying to in-file replace the characters between two given strings by 'X'. I have bunch of string pair, between which I want the replacement of characters by 'X' should happen.
In the below code, the first string in the pair is declared in cpi_list array. The second string in the pair is always either %26
or &
or ENDOFLINE
这就是我在做什么.
# list of "first" or "start" string
declare -a cpi_list=('%26Name%3d' '%26Pwd%3d')
# This is the "end" string
myAnd=\%26
newfile="inputlog.txt"
for item in "${cpi_list[@]}";
do
sed -i -e :a -e "s/\($item[X]*\)[^X]\(.*"$myAnd"\)/\1X\2/;ta" $newfile;
done
输入
CPI.%26Name%3dJASON%26Pwd%3dBOTTLE%26Name%3dCOTT
CPI.%26Name%3dVoorhees&machete
我要做到
CPI.%26Name%3dXXXXX%26Pwd%3dXXXXXX%26Name%3dXXXX
CPI.%26Name%3dXXXXXXXX&machete
PS:即使没有终点%26
,最后一项也需要将%26Name%3dCOTT
更改为%26Name%3dXXXX
,因为我正在寻找%26
作为终点或END OF THE LINE
PS: The last item need also change %26Name%3dCOTT
to %26Name%3dXXXX
even though there is no end %26
because I am looking for either %26
as the end point or the END OF THE LINE
但是以某种方式它不起作用.
But somehow it is not working.
推荐答案
这将在从任何UNIX安装中的任何shell调用的任何awk中工作:
This will work in any awk called from any shell in any UNIX installation:
$ cat tst.awk
BEGIN {
begs = "%26Name%3d|%26Pwd%3d"
ends = "%26|&"
}
{
head = ""
tail = $0
while( match(tail, begs) ) {
tgtStart = RSTART + RLENGTH
tgt = substr(tail,tgtStart)
if ( match(tgt, ends) ) {
tgt = substr(tgt,1,RSTART-1)
}
gsub(/./,"X",tgt)
head = head substr(tail,1,tgtStart-1) tgt
tail = substr(tail,tgtStart+length(tgt))
}
$0 = head tail
print
}
$ cat file
CPI.%26Name%3dJASON%26Pwd%3dBOTTLE%26Name%3dCOTT
CPI.%26Name%3dVoorhees&machete
$ awk -f tst.awk file
CPI.%26Name%3dXXXXX%26Pwd%3dXXXXXX%26Name%3dXXXX
CPI.%26Name%3dXXXXXXXX&machete
就像使用sed替代一样,beg和end字符串中的任何正则表达式元字符都需要转义,否则我们将不得不使用带有index()
而不是match()
的循环,因此我们需要进行字符串匹配而不是正则表达式匹配.
Just like with a sed subsitution, any regexp metacharacter in the beg and end strings would need to be escaped or we'd have to use a loop with index()
s instead of match()
so we'd do string matching instead of regexp matching.
这篇关于使用sed用char'X'替换两个字符串之间的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!