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 string?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With