Last active
February 19, 2018 20:48
-
-
Save viniciusdaniel/86f8cd1947d9615d4e706abb4c5c3a5b to your computer and use it in GitHub Desktop.
Regexp matches string and return only matched or group
This file contains 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
# 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}]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
OR
OR