-1

I have a file something like this:

dn: danan

cn: danian

cn: danian1


dn: danian2

cn: danian2


dn: danian3

cn: danian3

cn: danian4

all I want to do is grep the pattern "dn:" and print just the next 2 lines, but when I run grep -A 2 "dn:" the result is everything in the file, I just want to print the next 2 lines not the next 1 line

  • What do you mean with "he result is everything in the file, I just want to print the next 2 lines not the next 1 line,"? grep -A 2 should print the next 2 lines after each match. – finswimmer Jan 22 at 20:23
  • I mean , when I run grep -A 2 "dn:" the output is the next 2 lines and the next 1 line i just want to print the 2 next lines – danian Jan 22 at 20:57
  • root@danian:~# cat dare | grep -A 2 "dn:" dn: cn=danian@gmial.com cn: danian+@hotmail.com cn: danian2B@hotmail.com -- dn: daniandare1@hotmail.com cn: danian1@gf.es --> discard this line becouse is just 1 next line dn: daniandare2@hotmail.com cn: danian2@gf.es --> discard this line becouse is just 1 next line dn: danianlnx@hotmail.com cn: dana@gmail.com cn: fggh@dare.es – danian Jan 22 at 21:00
  • Do you mean you don't want to see "danian2" from the example, because it has only one line of "cn" text following it, instead of the two lines that the others have? – Jeff Schaller Jan 22 at 21:08
  • 1
    I think you need to put the desired output into the question where it can be legibly formatted instead of as a comment. Also, please read up on how to format a section as code in the question. – wef Jan 22 at 22:10
1

This might work:

$ awk -v RS="dn: " -v FS="\n" -v ORS="" 'NF>3 {print "dn:",$0}' input.txt

We define dn: as a record separator. The fields in one record are delimited by a new line character \n.

In case you have two lines following a line starting with dn:, before a new record starts with dn:, you will have 3 times a "\n" leading to 4 fields in the record. This is why we check if there are more than 3 fields in the record (NF>3). If that is the case, we print out the whole record, but need to prepend the dn:.

Note that NF>3 will find all records with more than two following lines in one record. If you want only those with exact two change it to NF==3.

If the blocks are delimited by a blank line (as it seems in one of your later comments) use this instead:

$ awk -v RS="\n\n" -v FS="\n" -v ORS="\n\n" 'NF>2 {print $0}' input.txt
  • 1
    Instead of piping to grep, you could pass in -v ORS="". – Niko Gambt Jan 23 at 5:43
  • Very good. I've edited my answer. – finswimmer Jan 23 at 5:45
-1

I run the command above and works perfectly,

awk -v RS="\n\n" -v FS="\n" -v ORS="\n\n" 'NF>2 {print $0}' 

the blocks delimited are blanck, it works perfectly.

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.