shellawkscripting

How to swap configuration entities within config files?


Apologies if the question has been asked before, really stuck on this issue for few hours which seems relatively easy. I got two patterns identified through awk in the single file.

awk '/\[code\.change\..*\]/ {found=1; print; next} found && NF {print} found && !NF {exit}' filename
awk '/\[code\.test\..*\]/ {found=1; print; next} found && NF {print} found && !NF {exit}' filename

Is there a possibility I can combine these two awks in one to swap the blocks?

an example of the config file is below file.cfg

[code.change.1]
file.path=filename
file.contact=manager
file.active=TRUE

[code.test.1]
ls -la filepath
pwd
find . -name filename

Just needs to swap the order of the configuration. Thanks


Solution

  • With the provided example, would you please try:

    awk -v RS= '                                                            # records are reparated by blank lines
        /^\[code\.change/ {pos1 = NR}                                       # position of the 1st block
        /^\[code\.test/ {pos2 = NR}                                         # position of the 2nd block
        {
            ary[NR] = $0                                                    # store the record in an array
        }
        END {
            tmp = ary[pos1]; ary[pos1] = ary[pos2]; ary[pos2] = tmp         # swap the two records
            for (i = 1; i <= NR; i++) print(ary[i], i<NR ? ORS : "")        # print the array
        }
    ' file.cfg