Updating the files at specific location

Hi All,

I have a requirement wherein I need to test if a line in file succeeding "IF" statement has "{" .If the line succeeding "IF" statement does not have "{" , then I need to insert the "{". Similarly , I need to check if a line in file preceding "ENDIF" statement has "}" .If not , then I need to insert the "{" as preceding line.

e.g. If a file file.txt has following content

$VAR1 = $VAR2 * $VAR3
IF( $VAR1 == 1) THEN
{
	IF ($VAR2 != 2) THEN
		IF($VAR3 = FLOOR($VAR)) THEN
			$VAR4 = $VAR1
				IF($VAR2 < 5) THEN
					PRINT($VAR2)
				}
				ENDIF
		ENDIF
	ENDIF
}
ENDIF

then I need to insert "{" after 2nd , 3rd and 4th "IF" Statement, also I need to insert "}" before 2nd and 3rd "ENDIF" Statement.

One more thing here is that , "{" and "}" to be inserted needs to same way indented as the preceding "IF" and succeeding "ENDIF".

e.g. The final file.txt that I need will be

$VAR1 = $VAR2 * $VAR3
IF( $VAR1 == 1) THEN
{
	IF ($VAR2 != 2) THEN
	{	
		IF($VAR3 = FLOOR($VAR)) THEN
		{
			$VAR4 = $VAR1
				IF($VAR2 < 5) THEN
				{
					PRINT($VAR2)
				}
				ENDIF
		}
		ENDIF
	}
	ENDIF
}
ENDIF

Can anyone please suggest a solution for this requirement ?

TIA

$ cat braces.awk

function pr_brace(b,c,s) {print substr(s, 1, index(s, c)-1)b}
$1=="ENDIF" && old1!="}" {pr_brace("}", "E", $0)}
old1~/^IF\(?/ && $1!="{" {pr_brace("{", "I", old0)}
{old0=$0; old1=$1; print}

$ awk -f braces.awk data

Thanks a lot alister. This works like charm :slight_smile: