Skip to content

Instantly share code, notes, and snippets.

@simon-brooke
Last active July 19, 2023 02:18
Show Gist options
  • Save simon-brooke/80c7237fe51e11619b92 to your computer and use it in GitHub Desktop.
Save simon-brooke/80c7237fe51e11619b92 to your computer and use it in GitHub Desktop.
I needed a little tool to do ifdefs, for conditional inclusion of text; I didn't want the full panoply of the C preprocessor. I like this. Test-driven development in awk.
#!/usr/bin/awk -f
# Experimental implementation of ifdef in awk
BEGIN {
depth = 0;
defined = "";
printing = 1;
}
$1 ~ /#DEFINE/ {
defined = defined ":" $2;
next;
}
$1 ~ /#IFDEF/ {
if (printing) {
printing = match( defined, $2);
}
if (!printing) {
depth ++;
}
next;
}
$1 ~ /#ENDIF/ {
depth --;
if (printing == 0 && depth < 1) {
printing = 1;
}
next;
}
{
if (printing) {
print($0);
}
}
#DEFINE test1
#DEFINE test3
1 This should print anyway.
#IFDEF test1
2 This should print because test1 is defined.
#ENDIF
3 This should print anyway.
#IFDEF test1
4 This should print because test1 is defined.
#IFDEF test2
5 This should NOT print because test2 is not defined.
#IFDEF test3
6 This should NOT print even though test3 is defined, because still in scope of test2.
#ENDIF
#ENDIF
7 This should print because out of scope of test2.
#ENDIF
8 This should print anyway.
#IFDEF test3
9 this should print because test3 is defined.
#IFDEF test2
10 This should not print because test2 is not defined.
#ENDIF
11 This should print because out of scope of test2.
#ENDIF
12 This should print anyway.
Summary: Lines 1, 2, 3, 4, 7, 8, 9, 11 and 12 should print; all
others should not.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment