Last active
November 6, 2015 00:28
-
-
Save mjwhitta/e7a8ff47d133831037f5 to your computer and use it in GitHub Desktop.
Attempt at implementing Powershell's select using bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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