In ksh script what is this BEGIN and END in this function?

Can Someone please explain why BEGIN and END statement is used inside function? How does that help in scripting?

function fileformatting
{
  CleanupMask="xXxX"

  sed 's/^.//' < ${AllFile} > ${AllFile}.tmp
  echo $(wc -l ${AllFile}.tmp)
       `awk -v CleanupMask=${CleanupMask} '
BEGIN { ; }
{

        inputstr=$0
        Num_Before_Clean_Mask = match(inputstr,CleanupMask)
        Num_After_Clean_Mask = Num_Before_Clean_Mask + 4
        DataString = substr(inputstr, Num_After_Clean_Mask)

        if (Num_Before_Clean_Mask != 0) print DataString

}

END { ; }
' ${AllFile}.tmp > ${AllFile} `

echo $(wc -l ${AllFile})
}

BEGIN and END are part of an awk script: called within the fileformatting ksh function:

as they contain no statements they could be removed e.g:

awk -v CleanupMask=${CleanupMask} '
{

        inputstr=$0
        Num_Before_Clean_Mask = match(inputstr,CleanupMask)
        Num_After_Clean_Mask = Num_Before_Clean_Mask + 4
        DataString = substr(inputstr, Num_After_Clean_Mask)

        if (Num_Before_Clean_Mask != 0) print DataString

}' ${AllFile}.tmp > ${AllFile}

In an awk script the BEGIN section runs once before any input is processed (e.g. to print file headers).
The END section is run once after all the input files have been processed (e.g. printing totals).

1 Like

That will fail if $AllFile contains whitespace.

}' "$AllFile.tmp" > "$AllFile"
1 Like