Skip to content

Instantly share code, notes, and snippets.

@valerio-bozzolan
Last active May 4, 2020 19:21
Show Gist options
  • Save valerio-bozzolan/6787675e931dce1ba7e9 to your computer and use it in GitHub Desktop.
Save valerio-bozzolan/6787675e931dce1ba7e9 to your computer and use it in GitHub Desktop.
Match parentesis subexpressions like `grep -E` (egrep) actually don't. In pure GNU Bash and no other dependency.
#!/bin/bash
########################################
# Match regex grep -E
# License: GNU GPL v3+
# Author: Valerio Bozzolan
########################################
function rtfm {
if [ ! -z "$2" ]; then
echo "Error: $2."
echo
fi
echo USAGE:
echo " $command REGEX [OPTIONS].."
echo
echo OPTIONS:
echo " -m --match NUM"
echo " NUM show the matching group (0: everything)"
echo " -t --text TEXT show a text"
echo
echo EXAMPLES:
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' 0
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' 1
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' 2
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' --text salt 0 --text pepper
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' --text salt 1 --text pepper
echo echo '"pino 123paolo456 piero"' \| $command '"[0-9]+([a-z]+)([0-9]+)"' --text salt 2 --text pepper
exit 2
}
command="$0"
regex="$1"
argc=$#
argv=($@)
if [ -z "$regex" ]; then
rtfm "Missing regex"
fi
while IFS= read -r ln; do
if [[ ! "$ln" =~ $regex ]]; then
continue
fi
glued=
for (( i=2, j=3; i<=argc; i++, j=i+1 )); do
arg1="${!i}"
arg2="${!j}"
case "$arg1" in
'--text'|'-t')
if [ -z "$arg2" ]; then
rtfm "Missing text after $arg1"
fi
glued="$glued$arg2"
(( i++ ))
;;
'--match'|'-m')
if [ -z "$arg2" ]; then
rtfm "Missing number after $arg1"
fi
glued="$glued${BASH_REMATCH[$arg2]}"
(( i++ ))
;;
*)
glued="$glued${BASH_REMATCH[$arg1]}"
;;
esac
done
if [ "$glued" ]; then
echo "$glued"
else
echo "$ln"
fi
done < /dev/stdin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment