ez bake
ez bake

Reputation: 21

Bash script to print pattern 1, search and print all lines from pattern 2 through Pattern 3, and print pattern 4

Please Help - I'm very rusty with my sed/awk/grep and I'm attempting to process a file (an export of a PDF that is around 4700 pages long).

Here is what I'm attempting to do: search/print line matching pattern 1, search for line matching pattern 2 and print that line and all lines from it until pattern 3 (if it includes/prints the line with pattern 3, I'm ok with it at this point), and search/print lines matching pattern 4.

All of the above patterns should occur in order (pattern 1,2,3,4) several hundred times in the file and I need to keep them in order.

Pattern 1: lines beginning with 1-5 and a whitespace (this is specific enough despite it seeming vague) Pattern 2: lines beginning with (all caps) SOLUTION: Pattern 3: lines beginning with (all caps) COMPLIANCE: Pattern 4: lines beginning with an IP Addresses

Here's what I've cobbled together, but it's clearly not working:

#!/bin/bash
#
sed '

/^[1-5]\s/p {

       /^SOLUTION/,/^COMPLIANCE/p {

                /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/p }

}' sample.txt

Upvotes: 2

Views: 400

Answers (2)

Ed Morton
Ed Morton

Reputation: 203712

You probably want something like this, untested since you didn't provide any sample input or expected output:

awk '
BEGIN         { state = 0 }
/^[1-5] /     { if (state ~ /[01]/) { block = $0; state = 1 } }
/^SOLUTION/   { state = (state ~ /[12]/ ? 2 : 0) }
state == 2    { block = block ORS $0 }
/^COMPLIANCE/ { state = (state == 2 ? 3 : state) }
/^([0-9]{1,3}\.){3}[0-9]{1,3}/ { if (state == 3) { print block ORS $0; state = 0 } }
' file

Upvotes: 1

midori
midori

Reputation: 4837

to use p in sed you need to use -n as well and also add -r for extended regex:

Here is how it should look like:

sed -r -n '{
/^[1-5] /p
/^SOLUTION/,/^COMPLIANCE/p
/^([0-9]{1,3}[\.]){3}[0-9]{1,3}/p
}' sample.txt

Upvotes: 1

Related Questions