I have a regex pattern that should match in several places in a string. I want all matching groups to be in the same array and then print each element.
So, I tried 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
Expected Result:
New match: Share1 New match: Share2
I think this will not work, because mine .+? matches greedy. So I looked at how this can be done with bash regex. But everyone seems to suggest using grep with the perl regex.
But, of course, there must be a different way. I was thinking maybe something like [^\\s]+ .. But the solution for this was:
New match: Share1 Disk New match: Share1
... any ideas?
bash regex regex-greedy
Forivin
source share