0
saaa vcahJJ HKak vk     
Import xxx xXXXXX xxxx
aaaa aaaa  aaaa ffffff
hhhhhh hhhhhh hhh hhh  hhhhhh
Error reading readStatus api
aaa hhhh aaa aaaaa
gggggggg ggggg xxxxxxxxxx
uuuu hhhhhhhh fffffffff
query run ends
qidIdih II v iQE Iqe

I want to find the 'Error' string in the file containing above logs and then print all the info available between 2 strings 'Import' and 'ends'. How can I do this using grep/sed Tried this but didn't get much. Note: I dont know how many lines will be before and after. It may vary from above sample I have provided

James Brown
  • 36,089
  • 7
  • 43
  • 59
Praveen
  • 31
  • 8

4 Answers4

0

Grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after.

grep -C 1 "Error" <logfile>

As per your requirement, You can use-

sed -n '/Import/,/ends/p' filename
Abhijeetk431
  • 847
  • 1
  • 8
  • 18
0

How about:

$ awk 'BEGIN{RS=ORS="ends\n"} /Error/' file

RS is the input record separator which needs to be ends. ORSgets the same value for output purposes. Also, your example had /^Error/ but Error does not start the record (^).

James Brown
  • 36,089
  • 7
  • 43
  • 59
0

Here you are:

out=$( sed -n '/^Import/,/end$/p' file )
echo "$out" | grep Error >/dev/null && echo "$out"

This will capture the text between "Import" and "end" and print it only if the extracted text contains "Error".

Fabien Bouleau
  • 464
  • 3
  • 11
0

You can try this sed

sed '/^Import/!d;:A;N;/\nImport/{h;s/.*\n//;bA};/ends$/!bA;h;s/\nError//;tB;d;:B;x' infile

Explanation :

sed '
/^Import/!d                 # if a line start with Import
:A
N                           # get an other line
/\nImport/{h;s/.*\n//;bA}   # if the last line start with Import
                            # keep only this last line and return to A
/ends$/!bA                  # If the last line end with ends
h                           # keep all the lines in the hold space
s/\nError//                 # look for a line which start with Error
tB                          # if find jump to B
d                           # not find, delete all and return to the start
:B
x                           # restore all the lines and print
' infile
ctac_
  • 2,413
  • 2
  • 7
  • 17