crazypaladin
crazypaladin

Reputation: 453

Sed three pattern search

Say I have a file as below. I want to do a three pattern search fetching all between [ and ] and which is having my search string(111) inside:

Msg: [
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
]
Msg: [
111
]
Msg: [
222
]

I see just below printed:

Msg: [
222
]

I tried pcregrep -M 'Msg:.*(\n|.)*]' but cant figure out how to get the wanted pattern alone. Please advise

Upvotes: 0

Views: 172

Answers (4)

Jotne
Jotne

Reputation: 41460

Here is a way to use gnu awk (Gnu to multiple characters in RS)

awk -v RS='Msg: \\[' '/111/ {print RS $0}' file
Msg: \[
111
]

This tell awk to split the post by Msg: [, then its just the pick the pattern and add the RS.

Upvotes: 0

Kalanidhi
Kalanidhi

Reputation: 5092

You can also use this way

sed  -n '/Msg: \[/N;/\n111/N;/\n\]/p' File_Name

Explanation :

/Msg: \[/N -- If the "Msg : [" the pattern is found get the another line and append to the pattern space  .    
/\n111/N   -- Then the new appended line is "111" again get the another line and append to the pattern space .
/\n\]/p    --The last line is "]" the print the pattern space and get your expect result.

Output :

Msg: [
111
]

Or you need that exact pattern use this way

sed  -rn '/Msg: \[/N;/\n111/N;/\n\]/s/^.*\n(.*)\n.*$/\1/p' File_Name

Output :

111

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

Sed version

sed '#n
 /Msg: \[/,/]/ {
    H
    /Msg: \[/ x
    /]/ {
       x
# next search pattern is your string
       s/111/&/p
       }
    }' YourFile

posix version so --posix on GNU sed

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174776

To get the number 111 only,

$ pcregrep -M -o '\]\nMsg:\s*\[\n\K[^\]\[]*(?=\n\]\nMsg:)' file
111

To get the whole block,

$ pcregrep -M -o '\]\n\KMsg:\s*\[\n[^\]\[]*\](?=\nMsg:)' file
Msg: [
111
]

Upvotes: 0

Related Questions