Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all lines between the one containing a certain string and another one containing another string PLUS the line before

Tags:

awk

I've spent some time searching the web, but didn't find the answer. Let's say I have a file containing the following lines :

aaaaaaa
vvvvv
ggggg
yyyyyyyyy
ffffff
rrrrrrrr
uuuuu
ssssssssssss
zzzzz
hhhhhhhh

I know how to find all lines from the one containing "ffffff" to the one containing "uuuuu" using awk :

awk '/ffffff/,/uuuuu/' file

But how can I get also the line preceding the first one I found (i.e. "yyyyyyyyy")? Is there something like grep -B 1 to do this? What I want to get is :

yyyyyyyyy
ffffff
rrrrrrrr
uuuuu

Thanks in advance.

like image 602
Stan the man Avatar asked Dec 23 '22 15:12

Stan the man


1 Answers

To only print if both ffffff and uuuuu exist in the input and not print a blank line if ffffff is the first line in the input:

$ cat tst.awk
/ffffff/ { f = 1 }
f {
    rec = rec $0 ORS
    if ( /uuuuu/ ) {
        printf "%s", rec
        f = 0
    }
    next
}
{ rec = $0 ORS }

$ awk -f tst.awk file
yyyyyyyyy
ffffff
rrrrrrrr
uuuuu
like image 168
Ed Morton Avatar answered Jun 29 '23 08:06

Ed Morton