Match 2 different patterns and print the lines

Hi,

i have been trying to extract multiple lines based on two different patterns as below:-

file1

@jkm|kdo|aas012|192.2.3.1 blablbalablablkabblablabla
sjfdsakfjladfjefhaghfagfkafagkjsghfalhfk
fhajkhfadjkhfalhflaffajkgfajkghfajkhgfkf
jahfjkhflkhalfdhfwearhahfl
@jkm|sdf|wud08q|168.2.1.3 bkblblblabdlablfbalflaflabfblaslfbalfblaf
gfrkqghfrkadegfeowfrkefewurfgefhjwavfss
gjgferjwgfrjewgfjrewgafrjgjwgrfjwgerjwg
we
@jkm|qpw|dgs901|192.2.45.3 blabslabdsa
ahfkghqewafroewforewfthewofghrwgh
whrgfrjwgflwgjh
@jkm|ppl|hfjsf87|192.2.3.8 bdfksfbdkbfdfbdgksdgbks
ksgfhglkshddlgsslghdlgh;lsdgj;sdkgs

I need to extract the ip address, for example: 192.2.3 and print all the lines start from "@" until it reaches the next "@" like below:-

output


@jkm|kdo|aas012|192.2.3.1 blablbalablablkabblablabla
sjfdsakfjladfjefhaghfagfkafagkjsghfalhfk
fhajkhfadjkhfalhflaffajkgfajkghfajkhgfkf
jahfjkhflkhalfdhfwearhahfl
@jkm|ppl|hfjsf87|192.2.3.8 bdfksfbdkbfdfbdgksdgbks
ksgfhglkshddlgsslghdlgh;lsdgj;sdkgs

for each line in bold (first line of each record), there is \n at the end.

the codes that i tried:-

awk '/^@/{p=0} /^@jkm/{p=1}p' file1

and tried to find and match 192.2.3. by grep and etc but did not get the right output. Can anyone tell me how to run two awk commands for implementing 2 different things one after another such as a case like this? I tried some that i found but none is successful. I am still trying my best to learn and understand awk and sed. Thanks

$ awk '/^@/{s = ($0~/192\.2\.3/) ? 1 : 0}s'  file

@jkm|kdo|aas012|192.2.3.1 blablbalablablkabblablabla
sjfdsakfjladfjefhaghfagfkafagkjsghfalhfk
fhajkhfadjkhfalhflaffajkgfajkghfajkhgfkf
jahfjkhflkhalfdhfwearhahfl
@jkm|ppl|hfjsf87|192.2.3.8 bdfksfbdkbfdfbdgksdgbks
ksgfhglkshddlgsslghdlgh;lsdgj;sdkgs
1 Like

Hi akshay Hegde,

i dont have gawk. :frowning:

Sorry I misread, Check I just modified my post, use nawk if you are on sunos / solaris

---------- Post updated at 11:16 AM ---------- Previous update was at 11:08 AM ----------

use this if you want to replace using shell variable

$ awk '/^@/{s = ($0~ip) ? 1 : 0}s' ip="192.2.3" file
$ ip="192.2.3"
$ awk '/^@/{s = ($0~ip) ? 1 : 0}s' ip="$ip" file
1 Like

Your codes work perfectly. Thanks so much. If u don't mind, can u explain briefly about your codes? :slight_smile: thanks

... on a side note, the ternary isn't necessary:

awk '/^@/{s=/192\.2\.3/}s' file
1 Like

It is a simple code and works great. Thanks :slight_smile:

Hi redse171,

Its very simple

$ awk '/^@/{s = ($0~ip) ? 1 : 0}s' ip="192.2.3" file

/^@/{.. --> Search for line which starts with @

s = ($0~ip) ? 1 : 0 --> Once @ is found, check whether line contains ip string/pattern which we are searching for, if pattern is found on line, s will be 1 (true) else s will be 0 (false)

..}s --> Print line whenever s is 1 (true)

1 Like

Thanks a million!! Now i understand.. it is simple :slight_smile: