I have a regex pattern that is supposed to match at multiple places in a string. I want to get all the match groups into one array and then print every element.
So, I've been trying this:
#!/bin/bash
f=$'\n\tShare1 Disk\n\tShare2 Disk\n\tPrnt1 Printer'
regex=$'\n\t(.+?)\\s+Disk'
if [[ $f =~ $regex ]]
then
for match in "${BASH_REMATCH[@]}"
do
echo "New match: $match"
done
else
echo "No matches"
fi
Result:
New match:
Share1 Disk
Share2 Disk
New match: Share1 Disk
Share2
The expected result would have been
New match: Share1
New match: Share2
I think it doesn't work because my .+?
is matching greedy. So I looked up how this could be accomplished with bash regex. But everyone seems to suggest to use grep with perl regex.
But surely there has to be another way. I was thinking maybe something like [^\\s]+
.. But the output for that was:
New match:
Share1 Disk
New match: Share1
... Any ideas?
[^\\s]+?
instead of.+?
. That will match characters until a whitespace if found. – Soonsooner[^\\s]+
which I have already mentioned in my question. I don't think that the?
is even supported in bash, I mean in this context.. I mean a?
behind a+
usually meansmatch ungreedy
. – BoursePOSIX regular expression
(which is what is used with=~
operator) does not have non-greedy quantifiers. – Shawnna[^\s]
is same as\S
. Use `\` for escaping if needed. – Soonsooner$match[1]
(Not good with bash). – Soonsooner${BASH_REMATCH[1]}
. – Preceding