Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed find pattern on line with another pattern

Tags:

regex

bash

sed

I am trying to extract text from a file between a < and a >, but only on a line starting with another specific pattern.

So in a file that looks like:

XXX Something here  
XXX Something more here  
XXX <\Lines like this are a problem> 
ZZZ something <\This is the text I need> 
XXX Don't need any of this

I would like to print only the <\This is the text I need>.

If I do

sed -n '/^ZZZ/p' FILENAME

it pulls the correct lines I need to look at, but obviously prints the whole line.

sed -n '/<\/,/>/p' FILENAME prints way too much. 

I have looked into grouping and tried

sed -n '/^ZZZ/{/<\/,/>/} FILENAME

but this doesn't seem to work at all.

Any suggestions? They will be much appreciated.

(Apologies for formatting, never posted on here before)

like image 261
user2962390 Avatar asked Mar 25 '26 23:03

user2962390


2 Answers

sed -n '/^ZZZ/ { s/^.*\(<.*>\).*$/\1/p }'
like image 160
pobrelkey Avatar answered Mar 28 '26 20:03

pobrelkey


If it does not have to be sed and you have a fairly recent grep, you may use grep's option -o as in

grep '^ZZZ' | grep -o '<[^>]*>'
like image 21
Harald Avatar answered Mar 28 '26 20:03

Harald



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!