Continuing a awk or sed print including a keyword until an end pattern is reached Continuing a awk or sed print including a keyword until an end pattern is reached unix unix

Continuing a awk or sed print including a keyword until an end pattern is reached


Your problem happens because both #< and ### match the "header" line, so you only print it and never loop. You also appended to the pattern buffer rather than consuming the lines one by one, so the header would always have been matched anyway.

Assuming you want to display the "header" and "errortext" of the "errorcode-024332", here's how I would do it :

sed -n '/#<.*<errorcode-024332>/{:start p;n;/###/!{b start}}'
  1. when we match the header line corresponding to our error code
  2. we print it
  3. we get the next line
  4. if the next line doesn't contain ###, we go back to step 2.

A quick test I did with your sample data :

$ echo "###<date> errortext <errorcode-xxxxx>errortexterrortext[...]errortexterrortext " | sed -n '/#<.*<errorcode-yyyy>/{:start p;n;/###/!{b start}}'###<date> errortext <errorcode-yyyy>errortexterrortext


You can use awk, like this:

awk -F'[<>-]' '/^#/{f=$(NF-1)}{print >> f; close(f)}' file.log

Let me explain it as a multiline version:

# Using this set of field delimiters it is simple to access# the error code in the previous last fieldBEGIN { FS="[<>-]"}# On lines which start with a '#'/^#/ {    # We set the output (f)ilename to the error code    f=$(NF-1)}# On all lines ...{    # ... append current line to (f)ilename    print >> f;    # Make sure to close the file to avoid running out of    # file descriptors in case there are many different error    # codes. If you are not concerned about that, you may    # comment out this line.    close(f)}