Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash grep newline

Tags:

grep

bash

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

Hi, I need to extract from the file:

first
second
third

using the grep command, the following line:

second
third

How should the grep command look like?

like image 439
Markus Avatar asked Aug 04 '09 15:08

Markus


2 Answers

Instead of grep, you can use pcregrep which supports multiline patterns

pcregrep -M 'second\nthird' file

-M allows the pattern to match more than one line.

like image 183
notnoop Avatar answered Oct 26 '22 08:10

notnoop


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.

like image 24
Andrew Y Avatar answered Oct 26 '22 08:10

Andrew Y