views:

56

answers:

2

Hi there! I have a simple log file which is very messy and I need it to be neat. The file contains log headers but are all jumbled up together therefore I need to sort the log files according to the log headers. There are no static number of lines that means that there is no fix number of lines for the each header of the text file. And I am using AWK to sort out the headers.

The Log files goes something like this:

Car LogFile Header
<text>
<text>
<text>
Car LogFile Header
<text>
Car LogFile Header
<and so forth>

It would be outputted like this:

Car LogFile Header
<text>
<text>
<text>
-------------------
Car Logfile Header
<text>
<text>

I have done up/searched a simple code but it does not seem to be working. Can someone please guide me? Thanks!

#!/bin/bash

# usage: pargrep <infile> <searchpattern>

inFile="$1"
searchString="$2"

awk '
BEGIN {
    FS="\n"
    RS="-----"
}
/'"$searchString"'/ { print }
' ${inFile}
A: 

It's better to use variable passing instead of trying to get complex quoting right.

#!/bin/bash

# usage: pargrep <infile> <searchpattern>

inFile="$1"
searchString="$2"

awk -v selector=$searchString '
    BEGIN {
        FS="\n"
        RS="-----"
    }
    selector ~ $0 { print }
    ' "${inFile}"
Dennis Williamson
Now it gives me the error of "awk: cmd. line:3: fatal: cannot open file `pargrep' for reading (No such file or directory)" ..... Any thoughts in that? Is that problem due to the extra usage calling?
JavaNoob
@JavaNoob: That sounds like a missing quotation mark to me.
Dennis Williamson
Its still not working....
JavaNoob
@JavaNoob: Same error message? What version of awk? What distribution of Linux?
Dennis Williamson
AWK version 3.1.5 and Red Hat 5.
JavaNoob
@JavaNoob: Then you shouldn't be getting that error message. Double check that you're not missing any single quotes `'` or double quotes `"` or have any extra of either.
Dennis Williamson
+1  A: 

Tweaking Dennis' answer a bit:

awk -v selector="$searchString" '
    BEGIN { 
        RS = "Car LogFile Header\n" 
        ORS = "------"
    }
    selector ~ $0 { 
        print RS $0 
    }
' "${inFile}"

Note that RS is the input record separator. I used ORS to illustrate.

I assume that "Car LogFile Header" is constant. If that is dynamic, let us know.

glenn jackman