Skip to content

Instantly share code, notes, and snippets.

@mjwhitta
Last active November 6, 2015 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjwhitta/e7a8ff47d133831037f5 to your computer and use it in GitHub Desktop.
Save mjwhitta/e7a8ff47d133831037f5 to your computer and use it in GitHub Desktop.
Attempt at implementing Powershell's select using bash
#!/usr/bin/env bash
usage() {
echo "Usage: ${0/*\//} [OPTIONS]"
echo "Options:"
echo " -d, --delimiter=DELIM"
echo " Use the specified delimiter (default: space)"
echo " -h, --help"
echo " Display this help message"
echo
echo "Empty fields or fields with DELIM in them will look weird"
echo "or even break. If DELIM is space, only the last column can"
echo "have spaces."
echo
exit $1
}
DELIM=" "
for arg in $@; do
case "$STORE" in
"delim") DELIM="$arg"
;;
esac
[ "$STORE" ] && unset STORE && continue
case "$arg" in
"-d"|"--delimiter") STORE="delim"
;;
"-h"|"--help") usage 0
;;
*) ARGS="$ARGS $arg"
;;
esac
done
set -- $ARGS
[ "$STORE" ] && usage 1
[ $# -eq 0 ] && cat /dev/stdin > /dev/stdout && exit
wanted=($ARGS)
indices=
first=t
while read line; do
OLD_IFS="$IFS"
IFS="$DELIM"
fields=($line)
IFS="$OLD_IFS"
if [ "$first" ]; then
let "num_fields = ${#fields[@]} - 1"
for want in ${wanted[@]}; do
let "count = 0"
for field in ${fields[@]}; do
if [ "$field" == "$want" ]; then
echo -n "${want}#"
indices="$indices $count"
break
fi
let "count += 1"
done
done
echo
unset first
continue
fi
for i in $indices; do
if [ "$i" == "$num_fields" ]; then
echo -n "${fields[@]:$i:${#fields[@]}}#"
else
echo -n "${fields[$i]}#"
fi
done
echo
done </dev/stdin | column -s "#" -t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment