添加 1 位数字(不包括 0x)来替换最后 4 位数字

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

我有以下文件(test.txt),我想更改逻辑如下:

0 becomes 1
1 becomes 2 
2 becomes 3 
3 becomes 4
4 becomes 5
5 becomes 6 
6 becomes 7 
7 becomes 8 
8 becomes 9
9 becomes 0

$ cat test.txt
69|1074330570|1,sip:+121345633210x3Bverstat=TN-Validation-Passed|tel:+12134565534|0
69|1077822111|2,;tel:+12223120011~sip:[email protected];|sip:[email protected]|0

我想更改最后 4 位数字,但当 x 紧邻 0x 时,则 0 不算数。 例如: 在第一行“+121345633210x”中,后 4 位是 3321。 在第二行中,'+12223120011',最后4位是0011和'+12223120051',最后4位是0051 输出应如下所示:

69|1074330570|1,sip:+121345644320x3Bverstat=TN-Validation-Passed|tel:+12134566645|0
69|1077822111|2,;tel:+12223121122~sip:[email protected];|sip:[email protected]|0

它需要排除“+1”,然后计算“10”位数字,其中我想替换第三列和第四列中的最后 4 位。

121345633210 becomes 121345644320 / 12134565534 becomes 12134566645
12223120011  becomes 12223121122  / 12223120051 becomes 12223121162 / 13123120022 becomes 13123121133

当列只是一个数字时,我使用了以下逻辑。但在这种情况下,它还有其他内容,因此下面的逻辑不起作用,但通过添加 1 位数字来转换数字是正确的。

awk -F"|" -v OFS="|" '
NR>0 {                                                      
    for (i=3;i<=4;i++) {                                   
        str = substr($i, 1, length($i) - 4)                 
        for (j = length($i) - 3; j <= length($i); j++) {    
            str = str (substr($i, j, 1) + 1) % 10           
        }
        $i = str                                            
    }
} 
1'
linux function awk replace substring
1个回答
0
投票

使用

gnu-awk
,您可以执行以下操作:

awk '
function rep(s,  i, r, ch) {
   for (i=1; i<=length(s); ++i) {
      ch = substr(s,i,1)
      r = r (ch == 9 ? 0 : ch+1)
   }
   return r
}
n = split($0, pn, /\+/) {
   for (j=2; j<=n; ++j) {
      if (match(pn[j], /([0-9]+)([0-9]{4})(0x)?(.*)/, a))
         pn[j] = a[1] rep(a[2]) a[3] a[4]
   }
   $0 = pn[1]
   for (j=2; j<=n; ++j)
      $0 = $0 "+" pn[j]
} 1' file

69|1074330570|1,sip:+121345634321x3Bverstat=TN-Validation-Passed|tel:+12134566645|0
67|1077822111|2,;tel:+12223121122~sip:[email protected];|sip:[email protected]|0
© www.soinside.com 2019 - 2024. All rights reserved.