Last active
January 23, 2017 06:48
-
-
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 (.*?)
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
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