Use awk or sed how can I print between the pattern (same pattern) only when the text in the middle of the pattern matches

advertisements

Using awk or sed how can i print between the pattern (same pattern) only when the text in the middle of the pattern matches For example suppose file contains

# Wed 10/12/2015
field1=a
field2=b
field3=c
field4=d
# Wed 10/12/2015
field1=e
field2=f
field3=g
field4=h
# Wed 10/12/2015
field1=i
field2=j
field3=k
field4=l

i want the block between two '#' to be printed where field3=g Below script i have written is not working

awk '$0 ~ /^#/{
       start_flag=1;
    }
    $0 ~ /g$/{
       mid_flag=1;
    }
    start_flag {
            n=NR;
            lines[NR];
    }
    $0  ~ /^#/
    {
       if (start_flag && mid_flag)
       {
            for (i=n; i<NR; i++)
            print lines[i];
       }
       start_flag=0;
       mid_flag=0;
       delete lines
    }' <file_name>

Expected o/p is

field1=e
field2=f
field3=g
field4=h


$ awk -v RS='#[^\n]*\n' -v ORS='' '/field3=g/' ip.txt
field1=e
field2=f
field3=g
field4=h

  • -v RS='#[^\n]*\n' set input record separator to be # upto and including next newline character
  • -v ORS='' set output record separator to empty string
  • /field3=g/ print all records containing the text field3=g

@NeronLeVelu suggests alternative to ensure # is matched at start of line

awk -v RS='(^|\n)[[:blank:]]*#[^\n]*\n' '/field3=g/' ip.txt