0

Trying to print lines with matched text within the range. This works fine if I use --START-- and --END-- as a pattern for range.

$ sed -n '/--START--/{:a;N;/--END--/!ba; /Device=A/p}' file
--START--
Device=A
Data=asdfasdf
Lorem=Ipsum
--END--
--START--
Device=A
Data=asdfasdf
--END--

But if I replace --END-- with empty line it stops working

file:
--START--
Device=A
Data=asdfasdf
Lorem=Ipsum

--START--
Device=A
Data=asdfasdf


$ sed -n '/--START--/{:a;N;/^$/!ba; /Device=A/p}' file

I guess sed doesn't recognize empty line pattern within curly braces. Please advise how to fix command to use empty line pattern instead of --END--

1
  • 1
    Are there spaces in the "blank" liines? od -bc file
    – waltinator
    Oct 5, 2020 at 14:27

1 Answer 1

2

The issue here is that - regardless of whether it is in a braced subexpression or not - /pattern/ is matched against the entire pattern space. As soon as you have a multiline pattern (via the use of N for example), it is impossible for ^$ to match (there will be at least a newline character between ^ and $).

GNU sed has a Multiline mode extension that

causes ^ and $ to match respectively (in addition to the normal behavior) the empty string after a newline, and the empty string before a newline

$ sed -n '/--START--/{:a;N;/^$/M!ba; /Device=A/p}' file
--START--
Device=A
Data=asdfasdf
Lorem=Ipsum

Otherwise, if you want to match a trailing empty line in a multiline pattern, you should be able to use \n$ explicitly ex.:

$ sed -n '/--START--/{:a;N;/\n$/!ba; /Device=A/p}' file
--START--
Device=A
Data=asdfasdf
Lorem=Ipsum
1
  • thank you for clear explanation
    – user947668
    Oct 5, 2020 at 17:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .