Regex with sed, search across multiple lines

前端 未结 2 1957
南笙
南笙 2021-02-09 20:59

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 \'/FIR         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 22:01

    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
    }'
    

提交回复
热议问题