files="*.jpg"
regex="[0-9]+_([a-z]+)_[0-9a-z]*"
#unquoted in order to allow the glob to expand
for f in $files
do
if [[ $f =~ $regex ]]
then
name="${BASH_REMATCH[1]}"
echo "${name}.jpg" # concatenate strings
name="${name}.jpg" # same thing stored in a variable
else
echo "$f doesn't match" >&2
# this could get noisy if there are a lot of non-matching files
fi
done
================================
It's better to put the regex in a variable. Some patterns won't work if included literally.
This uses =~
which is Bash's regex match operator.
The results of the match are saved to an array called $BASH_REMATCH
.
The first capture group is stored in index 1, the second (if any) in index 2,
etc. Index zero is the full match.
===================================
没有评论:
发表评论