Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep - show two parts of matching line

Tags:

regex

grep

zsh

I've read through the man page of grep and tried few things, none of them worked, at least not for me.

I want to extract a good readable line while tailing a log. This is a generic line in a log file I want to beautify:

26 Jan 2018 08:32:29,309 [TEXT] (myService-0) long.text.I.dont.care.about.but.is.different.in.every.line: [OTHERTEXT] Text im actually interested in

What I want is this:

26 Jan 2018 08:32:29,309 [TEXT] [OTHERTEXT] Text im actually interested in

I know that with grep -o -e ".*\[TEXT\]" I get the first part, and with grep -o -e "\[OTHERTEXT\].*", I get the second part.

But this is not displayed on one line, also not if I combine it into grep -o -e ".*\[TEXT\]" -e "\[OTHERTEXT\].*"

[TEXT] and [OTHERTEXT] always are there and are my 'separators', so can be used to support extracting the parts I need.

I initially thought I could use grep -o -e "(.*\[TEXT\]).*(\[OTHERTEXT\].*)" and then somehow use the matching groups $1 and $2, but either I don't see it or there is no way to do so.

Is there a way to achieve what I want?

Preferred is using grep (simply because I want to learn more about it), but if that is not possible then awk or sed are fine as well, it just has to be usable with a tail -f.

And I'm also open to other approaches to get to that point, so let me know what ways exist to get there.

Thanks, Tobias

like image 412
ximarin Avatar asked Jan 19 '26 03:01

ximarin


2 Answers

You can use sed:

sed -E 's/(\[TEXT]).*(\[OTHERTEXT])/\1 \2/' file.log

26 Jan 2018 08:32:29,309 [TEXT] [OTHERTEXT] Text im actually interested in

This sed matches a pattern between [TEXT] and [OTHERTEXT] and captures them in 2 groups. In replacement it puts those markers back using back-refrences \1 \2

like image 191
anubhava Avatar answered Jan 21 '26 19:01

anubhava


Using awk you could replace everything between ] and [ with ] [:

$ awk 'sub(/\].*\[/,"] [")' file
26 Jan 2018 08:32:29,309 [TEXT] [OTHERTEXT] Text im actually interested in
like image 20
James Brown Avatar answered Jan 21 '26 21:01

James Brown



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!