Assuming the data is structured so that it's always the line before and after that you want you can make use of grep's -A
(after) and -B
(before) switches to tell it to include the 1 line before the match and 1 line after it:
$ grep -A 1 -B 1 "42B" sample.txt
Pseudo name=Apple
Code=42B
state=fault
If you want the same number lines before and after the search term you can use the -C
(context) switch:
$ grep -C 1 "42B" sample.txt
Pseudo name=Apple
Code=42B
state=fault
If you'd like to be more stringent when matching the multiple lines you can use the tool pcregrep
, to match a pattern over multiple lines:
$ pcregrep -M 'Pseudo.*\n.*42B.*\nstate.*' sample.txt
Pseudo name=Apple
Code=42B
state=fault
The above pattern matches as follows:
-M
- multiple lines
'Pseudo.*\n.*42B.*\nstate.*'
- matches a group of strings where the first string starts with the word "Pseudo"
followed by any characters up until a end of line \n
, followed by any characters up until the string "42B"
followed by any characters up until another end of line (\n
), followed by the string "state"
followed by any characters.