How do I extract the last name into a full name array?
Suppose I have a fully qualified name in a bash array, I want to reliably extract the last name and not the last name (first name and second name if exists). For example, I show the following three examples to indicate the complexity of this problem.
x1=(John von Neumann)
x2=(Michael Jeffrey Jordan)
x3=(Michael Jordan)
Does anyone have a good way to extract last name and last name? Thank.
+3
source to share
1 answer
I am assuming that you are putting each distinct name in a separate array. A more flexible way is to use a regular expression. In normal English, the regex says - either the last name starts with a lowercase char followed by a few alphabetic characters and spaces - or the last name follows the last space in the string.
Take a look at this:
#!/bin/bash
x1=(John von Neumann)
x2=(Michael Jeffrey Jordan)
x3=(Michael Jordan)
x4=(Charles-Jean Etienne Gustave Nicholas de la VallΓ©e-Poussin)
regex="[[:space:]]([a-z]+.*|[A-Z][^[:space:]]+)$"
for i in 1 2 3 4
do
eval name=\${"x"$i[@]}
if [[ $name =~ $regex ]]; then
fullname=${BASH_REMATCH[1]}
echo $fullname
fi
done
0
source to share