# -*- awk -*- # hello world # print a simple string on stdout BEGIN { print "Hello World" } # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) BEGIN { print ARGV[1] } # env # access environment variable BEGIN { print ENVIRON["HOME"] } # test file exists # return exit code error (non zero) if a file does not exist BEGIN { if (system("[ -e /etc/mtab ]")) exit 1 } # test file readable # return exit code error (non zero) if a file is not readable BEGIN { if (system("[ -r /etc/mtab ]")) exit 1 } # formatting # print integers in a simple formatted string BEGIN { a=1; b=2; print a " + " b " = " a + b } # system # call an external program and check the return value BEGIN { if (system("false")) print "false failed" > "/dev/stderr" system("echo done") } # sed in place # remove #-comments from a file (modifying the file, i.e. in place) BEGIN { if (!("mktemp /tmp/sed.XXXXXX" | getline tmp)) exit 1 } { sub("#.*", ""); print >> tmp } END { system("cp -f " tmp " " ARGV[1]) system("rm -f " tmp) } # compile what must be # find and compile .c files into .o when the .o is old or absent BEGIN { while ("find -name '*.c'" | getline) { c = $0 sub(/.c$/, ".o") if (system(sprintf("[ %s -nt %s ]", c, $0)) == 0) { print "compiling", c, "to", $0 system(sprintf("gcc -c -o '%s' '%s'", $0, c)) } } } # grep # grep with -F -i -h handling, usage, grep'ing many files function usage() { print "usage: grep [-F] [-i] regexp [files...]" > "/dev/stderr" exit 1 } BEGIN { for (i = 1; i < ARGC; i++) { s = ARGV[i] ARGV[i] = "" if (s == "-h") usage() else if (s == "-i") IGNORECASE = 1 else if (s == "-F") F = 1 else break } if (i == ARGC) usage() re = s prefix = i + 2 < ARGC } { if (F ? index($0, re) : match($0, re)) print (prefix ? (FILENAME ":") : "") $0 }