Skip to content

Instantly share code, notes, and snippets.

@viniciusdaniel
Last active February 19, 2018 20:48
Show Gist options
  • Save viniciusdaniel/86f8cd1947d9615d4e706abb4c5c3a5b to your computer and use it in GitHub Desktop.
Save viniciusdaniel/86f8cd1947d9615d4e706abb4c5c3a5b to your computer and use it in GitHub Desktop.
Regexp matches string and return only matched or group
# String matcher for shell
# author: Vinícius Daniel Antunes Oliveira <viniciusdaniel@gmail.com>
# license: MIT <https://opensource.org/licenses/MIT>
#
#!/bin/bash
# Usage:
# cat /tmp/file | match.sh <regexp> [group match]
# match.sh <filename> <regexp> [group match]
# match.sh <string> <regexp> [group match]
#
#
# Receive pipe redirect
if [ ! -t 0 ] ; then
REGEX=$1;
TEXT=$(</dev/stdin);
if [ -z "$2" ]; then
GROUP=0;
else
GROUP=$2;
fi
else
INPUT=$1
REGEX=$2;
if [ -z "$3" ]; then
GROUP=0;
else
GROUP=$3;
fi
# Read file or by pass string
if [ -f "${INPUT}" ]; then
TEXT=$(<$INPUT);
else
TEXT=$INPUT;
fi
fi
[[ $TEXT =~ $REGEX ]] && [[ ! -z "${BASH_REMATCH[${GROUP}]}" ]] && echo "${BASH_REMATCH[${GROUP}]}"
@viniciusdaniel
Copy link
Author

viniciusdaniel commented Dec 6, 2016

Usage:

cat /tmp/file | match.sh <regexp> [group match]

OR

match.sh <filename> <regexp> [group match]

OR

match.sh <string> <regexp> [group match]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment