Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent sed from printing non-captured group [duplicate]

Tags:

regex

sed

I am using sed to capture and print only specific timestamps which are before 12pm (i.e. having 0 as first digit eg 09 as hours)

sed  -E 's/^.*\[(.* 0.*)\].*/\1/g'

However, it's also printing lines where no group is captured. How to avoid printing those?

Following is output of above command. Where regex matched, only captured group is printed and where it didn't match, original string is printed. I want to avoid printing string if regex is not matched.

2021/03/01 09:11:14
Accessed ([2021/03/01 12:32:36])
Accessed ([2021/03/01 16:48:29])
Accessed ([2021/03/01 19:40:03])
2021/03/02 08:53:27
Accessed ([2021/03/02 11:03:23])
Accessed ([2021/03/02 11:04:08])
Accessed ([2021/03/02 16:36:48])
Accessed ([2021/03/02 19:35:31])
2021/03/03 08:38:10
like image 718
Shashwat Kumar Avatar asked Jan 27 '26 07:01

Shashwat Kumar


1 Answers

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this sed to disable normal printing of unmatched lines:

sed -nE 's/^.*\[(.* 0.*)\].*/\1/p' file

Also please understand that .* is greedy in nature and due to lot of backtracking this pattern tends to get slower for large files.

I suggest using this regex with negated character class:

sed -nE 's/^[^[]*\[([^ ]* 0[^]]*)\].*/\1/p' file
like image 119
anubhava Avatar answered Jan 30 '26 01:01

anubhava



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!