Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print matching pattern only

Tags:

regex

grep

sed

awk

I need to print [PR:XXXXX] only.

Ex: [Test][PR:John][Finished][Reviewer:SE] to [PR:John] only. (PR tag)

Note:Other strings rather than the [PR:XXXXX] may changed time to time Ex:

[Test][PR:Cook][Completed]
[Test][Finished][PR:Russell][Reviewer:SE]
[Dump][Reviewer:SE][Complete][PR:Arnold]

Note: There are no multi line inputs and only one PR tag is included in all of inputs.

Untill I create following sed command but it did not work:

sed "s/\[PR:[^]]*\]//"
like image 700
Dhanushka Ekanayake Avatar asked Dec 05 '25 04:12

Dhanushka Ekanayake


1 Answers

You might use bash for this:

s='[Test][PR:Cook][Completed]'
regex='\[PR:[^]]*]'
[[ "$s" =~ $regex ]] && echo "${BASH_REMATCH[0]}"
# => [PR:Cook]

See this online demo.

You may use grep:

grep -o '\[PR:[^]]*]'

See this demo.

Or, you can use this sed:

sed -n 's/.*\(\[PR:[^]]*]\).*/\1/p'

See this online demo.

Or, you can use awk

awk 'match($0,/\[PR:[^]]*]/) {print substr($0,RSTART,RLENGTH)}'

See the online demo.

like image 166
Wiktor Stribiżew Avatar answered Dec 07 '25 18:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!