LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sed to display the pattern string, the line above it and the first line of that para (https://www.linuxquestions.org/questions/linux-newbie-8/sed-to-display-the-pattern-string-the-line-above-it-and-the-first-line-of-that-para-871976/)

rockie321 03-30-2011 03:37 PM

sed to display the pattern string, the line above it and the first line of that para
 
I need to grep for a particular string and if found need to display the line containing that string, the line above that and also the first line of that paragraph.

Can this be done via sed.
Thanks,

Eg, My Paragraphs

OA connectA
Enclosure:
Status: OK
Unit Identification LED: Off
Onboard Administrator:
Status: Critical
Power Subsystem:
Status: OK
Cooling Subsystem:
Status: OK

OA connectB
Interconnect Module #1 Status:
Health LED: OK
Interconnect Module #2 Status:
Health LED: Degraded
Interconnect Module #5 Status:
Health LED: OK
Interconnect Module #6 Status:


Here, if I grep for Critical, it should display the following

OA connectA <- The first line of the paragraph
Onboard Administrator: <- The line above the pattern string
Status: Critical <- The line containing the pattern string

similarly if I grep for Degraded, it should display

OA ConnectB
Interconnect Module #2 Status:
Health LED: Degraded

grail 03-31-2011 01:40 AM

Probably awk is better suited. Something like:
Code:

awk 'BEGIN{RS="";OFS=FS="\n"}/Critical|Degraded/{print $1;for(x=1;x<=NF;x++)if($x ~ /Critical|Degraded/)print $(x-1),$x;print ""}' file
You may want to use a variable in place of the regular expression so you can pass in what you like. I'll let you figure out that part :)

Kenhelm 03-31-2011 06:35 AM

For each paragraph this stores the first line in the hold space then has a sliding window of two lines in the pattern space.
Code:

sed -n '/./{
h          # Copy the first line into the hold space
:a
N          # Append next line to create a two line pattern space
/\n.*Critical/{x;p;x;p}  # Print if a match in the most recent line
s/.*\n//    # Remove the oldest of the two lines
/./ba      # If the remaining line is not empty go to :a
}' infile > outfile


rockie321 04-03-2011 02:48 PM

Thanks a lot to Kenhelm and grail. Got exactly what I needed.


All times are GMT -5. The time now is 09:02 AM.