[ACCEPTED]-regex match bash variable-bash
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 5 part is to retrieve the correct member from 4 BASH_REMATCH. Bash does not support non-capturing 3 parentheses, therefore Historian is either 2 under 1 or 2. Fortunately, we know it is 1 the last one.
Samples pure shell:
a="Historian (Level 1)"
noParens=${a/ \(*/}
lastWord=${noParens/[A-Za-z]* /}
a="Muster Historian (Level 1)"
noParens=${a/ \(*/}
lastWord=${noParens/[A-Za-z]* /}
(It's the same expressions 1 in both cases, just repeated for easy testing).
Based on "And I don't know how to match 6 on the $1 argument."
Have I understood you 5 correctly if what you are asking for is 4 not whether your regex is correct but rather 3 how to perform the match against the contents 2 of your bash variable?
matched_text=$(echo $yourbashvariablecontainingthetext | sed 's/your_regex/backreference_etc/')
$yourbashvariablecontainingthetext 1 should be your $1
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.