2

How can I view in less from the first instance of some arbitrary string "foo" to the last instance?

This arbitrary string will be on most every line of the log. I don't want to do grep "foo" bar.log | less because it won't be on each line that's relevant.

Let's say the file is

1 Don't care about
2 Care about (foo)
3 Care about (foo)
4 Care about
5 Care about (foo)
6 Don't care about

I am wondering how to get the following into less somehow,

2 Care about (foo)
3 Care about (foo)
4 Care about
5 Care about (foo)

grep "foo" bar.log | less will not work because it ignores line 4, which is one I care about.

  • you say "don't want to grep" but you tagged sed and grep; are you opposed to calling sed before less? – Jeff Schaller Mar 17 '16 at 15:23
  • So you want an interactive grep, one where you only get shown one result at a time and you can switch between them? – phk Mar 17 '16 at 15:28
  • @Jeff I don't mind at all, I just tagged with grep and sed because they seemed like the tools that would be able to do this. – Captain Man Mar 17 '16 at 15:31
  • This has been asked before more than once - here's just an example: How can I “grep” patterns across multiple lines? so in your case pcregrep -M 'foo.*(\n|.)*foo' infile – don_crissti Mar 17 '16 at 15:32
  • @phk no, that's not what I meant, I've updated with an example. – Captain Man Mar 17 '16 at 15:33
4

If you have awk you can do:

awk '/foo/{print b$0;b="";x=1;next} x{b=b$0"\n"}' bar.log | less

It buffers all lines since last occurence of foo in b variable.

  • Both this and @Stephane 's solution work. How do these stop on the last foo? – Captain Man Mar 17 '16 at 16:36
  • @CaptainMan only when foo appears, the lines since last foo are printed. – mik Mar 17 '16 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.