Skip to content

Instantly share code, notes, and snippets.

@hackjutsu
Last active January 23, 2017 06:48
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 hackjutsu/400e4fb810ad0e737da5a399154f909b to your computer and use it in GitHub Desktop.
Save hackjutsu/400e4fb810ad0e737da5a399154f909b to your computer and use it in GitHub Desktop.
[Example about doing regular expression match via Bash] Bash doesn't support non-greedy regex like (.*?)
str="asdkljfgaskdlgjkladsjfg123_abc_d4e5#asdfgerhgreg"
regex="[0-9]+_([a-z]+)_[0-9a-z]*"
if [[ $str =~ $regex ]]
then
name="${BASH_REMATCH[1]}"
echo "${name}.jpg" # 123_abc_d4e5.jpg
name="${name}.jpg" # same thing stored in a variable
else
echo "$str doesn't match" >&2
fi
# This uses =~ which is Bash's regex match operator. The results matched
# by (..) are saved to an array called $BASH_REMATCH. The first capture
# group is stored in index 1, the second (if any) in index 2, Index zero
# is the full match.
# http://stackoverflow.com/a/1892107/3697757
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment