0
votes

I have 2 text files. file1.txt, file2.txt

I need to replace all characters from line 3 to line 5, column 3 to column 5 of file1.txt with line 8 to line 10, column 4 to column 9 of file2.txt.

To make a better understanding, I'm replace a rectangular region of a text file, with a rectangular region found in another file. Notice, the rectangle in file2.txt is several columns longer.

Thanks!

1

1 Answers

1
votes

A parameterized solution:

L1  = starting line in file1
L2  = starting line in file2
N   = number of lines
F1a = starting field in file1
F1b = ending field in file1
F2a = starting field in file2
F2b = ending field in file2

awk -vL1=3 -vL2=8 -vN=3 -vF1a=3 -vF1b=5 -vF2a=4 -vF2b=9 '

    FNR == NR {
        if (FNR >= L2 && FNR < L2 + N) {
            a[FNR - L2] = $F2a
            for (i = F2a + 1; i <= F2b; ++i)
                a[FNR - L2] = a[FNR - L2] OFS $i
        }
        next
    }

    FNR >= L1 && FNR < L1 + N {
        for (i = 1; i < F1a; ++i)
            printf("%s%s", i == 1 ? "" : OFS, $i)
        printf("%s%s", F1a == 1 ? "" : OFS, a[FNR - L1])
        for (i = F1b + 1; i <= NF; ++i)
            printf("%s%s", OFS, $i)
        print""
        next
    }

    1

' file2.txt file1.txt