Skip to content

Instantly share code, notes, and snippets.

/fawk

Created November 21, 2014 21:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8cfd9652085061dbebf5 to your computer and use it in GitHub Desktop.
Save anonymous/8cfd9652085061dbebf5 to your computer and use it in GitHub Desktop.
A Bash shell function to save your fingers from typing "awk '{ print $5 }'" all the time
# Inspiration: http://serverfault.com/a/5551 (but basically rewritten)
function fawk() {
USAGE="\
usage: fawk [<awk_args>] <field_no>
Ex: getent passwd | grep andy | fawk -F: 5
"
if [ $# -eq 0 ]; then
echo -e "$USAGE" >&2
return
#exit 1 # whoops! that would quit the shell!
fi
# bail if the *last* argument isn't a number (source:
# http://stackoverflow.com/a/808740)
last=${@:(-1)}
if ! [ $last -eq $last ] &>/dev/null; then
echo "FAWK! Last argument (awk field) must be numeric." >&2
echo -e "$USAGE" >&2;
return
fi
if [ $# -gt 1 ]; then
# Source:
# http://www.cyberciti.biz/faq/linux-unix-bsd-apple-osx-bash-get-last-argument/
rest=${@:1:$(( $# - 1 ))}
else
rest='' # just to be sure
fi
awk $rest "{ print \$$last }"
} # fawk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment