In bash script, what is the easy way to extract a text pattern from a string?
For example, I want to extract X
followed by 2 digits in the end of the st
There's a nifty =~
regex operator when you use double square brackets. Captured groups are made available in the $BASH_REMATCH
array.
if [[ $STRING =~ (X[0-9]{2})$ ]]; then
echo "matched part is ${BASH_REMATCH[1]}"
fi
You can also use parameter expansion:
V="abcX23"
PREFIX=${V%%X[0-9][0-9]} # abc
SUFFIX=${V:${#PREFIX}} # X23
Lets take your input as
Input.txt
ASD123
GHG11D3456
FFSD11dfGH
FF87SD54HJ
And the pattern I want to find is "SD[digit][digit]"
Code
grep -o 'SD[0-9][0-9]' Input.txt
Output
SD12
SD11
SD54
And if you want to use this in script...then you can assign the above code in a variable/array... that's according to your need.
$ foo="abcX23"
$ echo "$(echo "$foo" | sed 's/.*\(X[0-9][0-9]\)$/\1/')"
X23
or
if [[ "$foo" =~ X[0-9][0-9]$ ]]; then
echo "${foo:$((${#foo}-3))}"
fi
I need to extract the host port from this string: NIC 1 Rule(0): name = guestssh, protocol = tcp, host ip = , host port = 2222, guest ip = , guest port = 22
That string is obtained by using: vboxmanage showvminfo Mojave | grep 'host port', I mean is filtered and I need to extract whatever number be in the host port; in this case is 2222 but it can be different.