2

Following Input File:

#Report Nr. 2343215
#Errors 3243
#Date: (Timestampt)
#Informaiton
#
# Headers
# Specs
DLSLWD 0 0 0 0 Jun 22 01:51:16PM 2018
#List of Objects
#
# Headers
# Paths
Files not found /var/xxxxx
Files not found /etc/xxxxx
Files not found /mnt/xxxxx
Files not found /safd/xxxxx
#
#Reports
#
Error-Number 123
Error Number 12345
#

What i need is an awk that pipes the "List of Objects" into a new file:

#List of Objects
#
# Headers
# Paths
Files not found /var/xxxxx
Files not found /etc/xxxxx
Files not found /mnt/xxxxx
Files not found /safd/xxxxx
#  

And the " Reports"into a differnt file:

#Reports
#
Error-Number 123
Error Number 12345
#

It's a match for #List of Objects + 3 lines until "first" #.

Same for the Reports: Match #Reports + 1 line until "first" #.

At first i tried something like:

awk '/#List of Objects/,/#Reports/'

For the list of objects followed by:

awk '/#Reports/,0'

To get the data from #Reports until EOF.

But because #Reports and #List of Objects are both OPTIONAL and not in every input file I can't use #Reports as the "END-Pattern". so, I have to match on the # but ignore the first X occurrences of # after the matching pattern.

0
1

Awk script:

extract_pat_space.awk contents:

$0 ~ "^#" pat{ f = 1; hash = 0 }
f { print }
NF == 1 && $1 == "#"{ 
    if (++hash == 2) { f = hash = 0 }
}

Usage (for both patterns):

$ awk -f extract_pat_space.awk -v pat="List" file > list_of_objects.txt
$ awk -f extract_pat_space.awk -v pat="Reports" file > reports.txt

Results:

$ cat list_of_objects.txt 
#List of Objects
#
# Headers
# Paths
Files not found /var/xxxxx
Files not found /etc/xxxxx
Files not found /mnt/xxxxx
Files not found /safd/xxxxx
#

$ cat reports.txt 
#Reports
#
Error-Number 123
Error Number 12345
#
2
  • i have no idea what you are doing with this awk, i'm trying to get my head around it, thank you! is it also possible to get rid of all the lines with a # in the output? I would just do a grep -ve '#" on it but would be nice to have this in the awk scrip too. – T-One Jun 27 '18 at 15:10
  • @T-One, extend your question according to the mentioned moment – RomanPerekhrest Jun 27 '18 at 15:13
1
awk '
    /#List of Objects/ {f = "objects.txt"} 
    /#Reports/         {f = "reports.txt"} 
    f                  {print > f}
' file

When you see one of the key headers, set the output filename.
If the variable has been set, print to that file.

2
  • This looks extremly simple, how does awk know where to stop? – T-One Jun 28 '18 at 7:27
  • Stop? At the end of file. Are there other criteria I missed? – glenn jackman Jun 28 '18 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.