Marcin Król
Marcin Król

Reputation: 1654

Regex with sed, search across multiple lines

I'd like to concatenate a few lines, perform a regex match on them and print them. I tried to do that with sed.

Namely, I used:

cat add | sed -rn '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/s/SOME_REGEX/&/p'

It prints only the lines that match SOME_REGEX while I expect it to concatenate the lines from the range between FIRST_LINE and LAST_LINE and print the concatenation if it matches SOME_REGEX.

Upvotes: 6

Views: 11438

Answers (2)

Kevin Lee
Kevin Lee

Reputation: 718

sed -n '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/p' add | sed -n '/FIRST_LINE_REGEX/ b check; H; $ b check; b; :check; x; /SOME_REGEX/p'

The motivation of the second pipe part comes from here: https://stackoverflow.com/a/6287105/992834

Edit: Amended for when SOME_REGEX is in between.

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208405

When using '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/' each line is still processed separately, to concatenate lines you need to use the hold space or the N command to append the next line to the pattern space. Here is one option:

cat add | sed -rn '/FIRST_LINE_REGEX/{:a;N;/LAST_LINE_REGEX/{/SOME_REGEX/p;d};ba}'

Commented version:

cat add | sed -rn '/FIRST_LINE_REGEX/ {  # if line matches /FIRST_LINE_REGEX/
  :a                                       # create label a
  N                                        # read next line into pattern space
  /LAST_LINE_REGEX/ {                      # if line matches /LAST_LINE_REGEX/
    /SOME_REGEX/p                            # print if line matches /SOME_REGEX/
    d                                        # return to start
  }
  ba                                       # return to label a
}'

Upvotes: 10

Related Questions