Search code examples
linuxawksedreplace

Replace String In a File


I have a file as following

ID,SEQ,PO_NUM,BATCH,CREATE_DT
99001100788259,127856626,111,20230801
99001100788270,223412976,111,20230801
99001100788281,112120972,222,20230801

I want to replace the first two columns last 4 digits by adding 1 digit to each number as following:

99001100789360,127857737,111,20230801
99001100789381,223413087,111,20230801
99001100789392,112121083,222,20230801

0 should become 1 1 should become 2 2 should become 3 3 should become 4 4 should become 5 5 should become 6 6 should become 7 7 should become 8 8 should become 9 9 should become 0

I tried sed but not able to figure out the last 4 digits logic.


Solution

  • Here is one potential solution:

    awk 'BEGIN {
        FS = ","
    }
    
    NR == 1 {
        print
    }
    
    NR > 1 {
        a = split($1, b, "")
        c = split($2, d, "")
        e = split($0, f, "")
        for (i = 1; i <= e; i++) {
            if (i > a - 4 && i <= a) {
                printf "%s", (f[i] + 1 == 10 ? "0" : f[i] + 1)
            } else if (i > a + c - 3 && i <= a + c + 1) {
                printf "%s", (f[i] + 1 == 10 ? "0" : f[i] + 1)
            } else {
                printf "%s%s", f[i], (i == e ? "\n" : "")
            }
        }
    }' file.txt
    ID,SEQ,PO_NUM,BATCH,CREATE_DT
    99001100789360,127857737,111,20230801
    99001100789381,223413087,111,20230801
    99001100789392,112121083,222,20230801