Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Last active February 5, 2024 22:26
Show Gist options
  • Save mortymacs/dc5c2dc1cb713f495bf5a0f10b437c23 to your computer and use it in GitHub Desktop.
Save mortymacs/dc5c2dc1cb713f495bf5a0f10b437c23 to your computer and use it in GitHub Desktop.
Sample AWK
#!/bin/sh
# Iterate over a csv file and aggregate items.
# in BEGIN we define global variables.
# in the middle block we define the logic.
# in the END we define the conclusion logic like prints etc.
# NR>1 means ignore the first line.
awk -F "," 'BEGIN {
delete visited_items;
}
NR>1 {
visited_items[$2] += $3;
}
END {
for(item in visited_items) {
print item "=" visited_items[item];
}
}' sample.csv
#!/usr/bin/env awk -f
function say_hello(name) {
print "Hello " name
}
function say_bye(name) {
print "Goodbye! " name
}
BEGIN {
name = "Mort";
}
{
say_hello(name);
exit;
}
END {
say_bye(name);
}
ID NAME RANK
1 A 20
2 B 9
3 C 7
4 D 15
5 A 8
6 R 18
7 Z 12
#!/bin/sh
# Iterate over a csv file and tell us what ranks are more than 10 and what are less than 10.
# in BEGIN we define global variables.
# in the middle block we define the logic.
# in the END we define the conclusion logic like prints etc.
# NR>1 means ignore the first line.
awk -F "," 'BEGIN {
passed = 0;
failed = 0;
}
NR>1 {
if ($3 >= 10) {
passed += 1;
} else {
failed += 1;
}
}
END {
print "PASSED:" passed;
print "FAILED:" failed;
}' sample.csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment