简体   繁体   中英

Double Search and Print using Awk/Sed

I need a command to extract data from below data, For example I need data corresponding to 3_xloc_7 and 3_yloc_14 (Need to match both lines) and print until 3_lsep .

a  
b  
3_xloc_7  
3_yloc_12  
c  
dsa  
gdf  
3_lsep  
3_xloc_6  
3_yloc_14  
asfdf  
dsdfgsd  
gsfsd  
tdg  
3_lsep  
3_xloc_7  
3_yloc_14  
a  
d  
g  
3_lsep  

I used this command,

sed -n '/3_xloc_7/h;{/3_yloc_14/{x;G;};//,/3_lsep/p}'

but it gives wrong data.

Expected o/p:

3_xloc_7  
3_yloc_14  
a  
d  
g  
3_lsep  

O/P: (It is giving o/p of 3_xloc_6 and 3_yloc_14 )

3_xloc_7  
3_yloc_14  
asfdf  
dsdfgsd  
gsfsd  
tdg    
3_lsep  

This gnu awk (gnu due to multippel characters in Record Selector) may do:

awk -v RS='3_lsep' '/3_xloc_7/ && /3_xloc_14/ {print $0RS}' file

3_xloc_7
3_xloc_14
a
d
g
3_lsep
  • RS='3_lsep' Set record selector to 3_lsep . Makes awk work with block of text.
  • /3_xloc_7/ && /3_xloc_14/ search for block containing both 3_xloc_7 and 3_xloc_14
  • print $0RS print block and record selector

Another version:

awk '/3_xloc_7/ {s=$0;t=NR} t+1==NR && /3_xloc_14/ {print s;f=1} f; /3_lsep/ {f=0}' file
3_xloc_7
3_xloc_14
a
d
g
3_lsep
  • /3_xloc_7/ if 3_xloc_7 is found, do
    • set s=$0 (store the line) and t=NR (get current line number)
  • t+1==NR && /3_xloc_14/ if t+1==NR if this is the next line and it contains /3_xloc_14/ do:
    • {print s;f=1} print previous line and set f to 1
  • f; if f is true do the default action, print
  • /3_lsep/ {f=0} if line contains 3_lsep set f to 0 to stop printing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM