bash grep newline

后端 未结 11 1760
渐次进展
渐次进展 2021-01-04 12:38

[Editorial insertion: Possible duplicate of the same poster\'s earlier question?]

Hi, I need to extract from the file:

first
second
         


        
11条回答
  •  情话喂你
    2021-01-04 13:15

    Your question abstract "bash grep newline", implies that you would want to match on the second\nthird sequence of characters - i.e. something containing newline within it.

    Since the grep works on "lines" and these two are different lines, you would not be able to match it this way.

    So, I'd split it into several tasks:

    1. you match the line that contains "second" and output the line that has matched and the subsequent line:

      grep -A 1 "second" testfile
      
    2. you translate every other newline into the sequence that is guaranteed not to occur in the input. I think the simplest way to do that would be using perl:

      perl -npe '$x=1-$x; s/\n/##UnUsedSequence##/ if $x;'
      
    3. you do a grep on these lines, this time searching for string ##UnUsedSequence##third:

      grep "##UnUsedSequence##third"
      
    4. you unwrap the unused sequences back into the newlines, sed might be the simplest:

      sed -e 's/##UnUsedSequence##/\n'
      

    So the resulting pipe command to do what you want would look like:

    grep -A 1 "second" testfile | perl -npe '$x=1-$x; s/\n/##UnUsedSequence##/ if $x;' | grep "##UnUsedSequence##third" | sed -e 's/##UnUsedSequence##/\n/'
    

    Not the most elegant by far, but should work. I'm curious to know of better approaches, though - there should be some.

提交回复
热议问题