使用 sed 用 char 'X' 替换两个字符串之间的所有字符 [英] Substitute all characters between two strings by char 'X' using sed

查看:19
本文介绍了使用 sed 用 char 'X' 替换两个字符串之间的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Bash 脚本中,我试图在文件中用X"替换两个给定字符串之间的字符.我有一堆字符串对,我希望在它们之间用X"替换字符.
在下面的代码中,对中的 第一个 字符串在 cpi_list 数组中声明.对中的第二个字符串总是%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")/1X2/;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:最后一项也需要将 %26Name%3dCOTT 更改为 %26Name%3dXXXX 即使没有结束 %26 因为我正在寻找 %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()s 而不是 的循环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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆