LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   shell script find a line and the next line (grep?) (https://www.linuxquestions.org/questions/programming-9/shell-script-find-a-line-and-the-next-line-grep-572009/)

metalx1000 07-24-2007 06:53 PM

shell script find a line and the next line (grep?)
 
Lets say I have the following text file

Code:

name
john123

phone:
123-213-4566

name
chris035

phone:
236-555-6546

name
bob56

phone:
333-666-9852

is there a way to find all the line that have "phone" and print them and the next line to make the out put look like this:
Code:

phone:
123-213-4566
phone:
236-555-6546
phone:
333-666-9852

I've looked into using grep awk & sed

I'm sure there is a way but I have yet to find it.

chrism01 07-24-2007 07:00 PM

grep -A1 phone $file


This only works with GNU grep. Normal grep doesn't have -A (after) option ( see also -B => before)

dxqcanada 07-24-2007 07:02 PM

Awk

Awk can handle multiline records by specifying the field separator to be a newline and set the record separator to an empty string.

homey 07-24-2007 07:13 PM

Here's an example using sed.
Code:

sed -n '/phone/,+1 p' file.txt

metalx1000 07-24-2007 08:25 PM

All great answers.

Thanks!!!

ghostdog74 07-24-2007 08:41 PM

Code:

awk '/phone/{where=NR;print}NR==where+1 && where!=0 {print}' file


All times are GMT -5. The time now is 01:58 AM.