I am trying to modify a bash script. The script current contains
print "<div class=\"title\">" $1 "</div>"
Where $1
may look like:
Apprentice Historian (Level 1)
Historian (Level 4)
Master Historian (Level 7)
What i'd like to do is add an image which is named the "base" value. I had something like this in mind:
print "<div class=\"icon\"><imgsrc=\"icons\" $1 ".png\"></div><div class=\"title\">" $1 "</div>"
However, in this case I'd like $1
to only return Historian
. I was thinking I could use a regex to match and on $1
and keep only the part I need.
(Apprentice|Master)?\s(.*)\s(\(Level \d\))
I know my regex isn't quite there, ideally apprentice/master would be in their own match group and not tied the base. And I don't know how to match on the $1
argument.
You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.
$BASH_REMATCH is an array and contains the matched text snippets. ${BASH_REMATCH[0]} contains the complete match. The remaining elements, e.g. ${BASH_REMATCH[1]} , contain the portion which were matched by () subexpressions.
A regular expression (regex) is a text pattern that can be used for searching and replacing. Regular expressions are similar to Unix wild cards used in globbing, but much more powerful, and can be used to search, replace and validate text.
A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.
Using regex matching in bash:
for a in 'Apprentice Historian (Level 1)' 'Historian (Level 4)' 'Master Historian (Level 7)' ; do
set "$a"
echo " === $1 ==="
[[ $1 =~ (Apprentice|Master)?' '?(.*)' ('Level' '[0-9]+')' ]] \
&& echo ${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}
done
The tricky part is to retrieve the correct member from BASH_REMATCH. Bash does not support non-capturing parentheses, therefore Historian is either under 1 or 2. Fortunately, we know it is the last one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With