Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract pattern from a string

Tags:

bash

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?

like image 759
user1533326 Avatar asked Jul 18 '12 01:07

user1533326


2 Answers

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
like image 163
John Kugelman Avatar answered Oct 18 '22 21:10

John Kugelman


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.

like image 40
Debaditya Avatar answered Oct 18 '22 23:10

Debaditya