1

I have a file as shown below:

FHEAD01
THEAD02
TCUST03
TITEM04
TITEM05
IDISC06
TTEND07
TTAIL08
THEAD09
TCUST10
IDISC11....
TITEM12
TTEND13
TTAIL14
THEAD15
TITEM16
IDISC17
TTEND18
TTAIL19
THEAD20
IDISC21.....
TITEM22
TTEND23
TTAIL24
THEAD25
TITEM26
IDISC27
IDISC28
TITEM29
TTEND30
TTAIL31
FTAIL32

I want to identify the following sequence and print records:

1) THEAD,TCUST,IDISC,*
2) THEAD,IDISC,*

Expected Output Following records should be printed

THEAD09
TCUST10
IDISC11
THEAD20
IDISC21

I tried the following code, but it is not giving results:

awk '/THEAD/; /TCUST/ ; /IDISC/ ' test1.dat
| improve this question | | | | |
  • 2
    What sequence? What records should be printed? Please edit your question and clarify your requirements. At least add your desired output sow e can understand what you need. – terdon Dec 15 '16 at 12:42
  • Also, from what I've gathered so far, why not use egrep? – schaiba Dec 15 '16 at 12:48
  • edited the question and added expected output – Amit Dec 15 '16 at 12:53
  • So you want to print all lines starting with THEAD if i) the next line starts with TCUST and ii) the line after that starts with IDISC. If all three conditions are met, you want to print all three lines. Then, you also want all lines starting with THEAD where the next line starts with IDISC but only print two lines. Is that more or less correct? – terdon Dec 15 '16 at 12:57
  • @terdon.. Yes exactly this is my requirement. – Amit Dec 15 '16 at 12:59
1
awk '
    /THEAD/{
        p=$0                 #store line with `THEAD`
        getline              #read next line from file
        if(/TCUST/){         #if there is `TCUST` in it
            p=p ORS $0       #add it to `p` vaiable
            getline          #and get next line from file
            }
        if(/IDISC/)          #if there is `IDISC` in line
            print p ORS $0   #print `p` variable altogether with line
    }
    ' test1.dat
| improve this answer | | | | |
  • this is working well. Could you please explain the code? – Amit Dec 16 '16 at 7:01
  • @Amit See updated – Costas Dec 16 '16 at 9:32

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.