Alex Rivera | Logout

bash grep newline

Asked 2009-08-04T15:38:50.703
13

[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?

Edit
Report

2 Answers

9

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.

answered 2009-08-04T16:04:28.543
2

I don't really understand what do you want to match. I would not use grep, but one of the following:

tail -2 file         # to get last two lines
head -n +2 file      # to get all but first line
sed -e '2,3p;d' file # to get lines from second to third

(not sure how standard it is, it works in GNU tools for sure)

answered 2009-08-04T15:49:32.100

Your Answer