Issue
I need to print blocks of text that start one line before a pattern matches till the next blank line. I managed to do it with awk
/sed
but starting from the line that PATTERN2 (passed as variable $ID
) appears and not the previous one. My inputfile:
2022/12/28 02:06:29 [Time]
Processing id: PATTERN1
multiple lines follow
2023/01/14 04:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
2023/02/15 08:07:29 [Time]
Processing id: PATTERN3
multiple lines follow
2023/02/16 14:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
....
with sed:
sed -n "/Processing id: $ID/,/^$/p" inputfile
with awk:
awk -v myid="$ID" '$0 ~ "Processing id: "myid,/^$/ {print}' inputfile
Desired output:
2023/01/14 04:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
2023/02/16 14:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
Solution
With awk
, using RS=""
to define blank-line separated records, and a conditional action with the ~
includes operator:
pattern="PATTERN2"
awk -v myid="$pattern" 'BEGIN{RS=""; ORS="\n\n"} $0 ~ myid' inputfile
Output:
2023/01/14 04:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
2023/02/16 14:06:29 [Time]
Processing id: PATTERN2
multiple lines follow
Answered By - Dave Pritlove Answer Checked By - Willingham (WPSolving Volunteer)