tags:

views:

30

answers:

3

I have a file in the format:

Port Number
IP address
Port Number
IP address

(Not sure how the output will be displayed here but let me tell you they are on separate lines)

and so on....

I use the command grep -C 1 'port number' file.txt i.e. I want all IP addresses corresponding to a particular port. Making it simple, I want the next line matching a regular expression. Like if my regular expression matches line 2,4 and 6 then I want lines 3, 5 and 7 to be printed. How to do that?

+1  A: 

sed -n '/^port$/{n;p}' < file.txt

-n tells sed not to print the input text as it processes it. You want this since you only want to see the lines which match your criteria.

/^port$/ restricts which lines {n;p} will operate on to those matching the specified port.

In {n;p}, the n means to read the next line of input into sed's pattern space. This will be the line that contains your IP address. The p then tells sed to print its pattern space, so the IP address line is printed.

jamessan
This deletes all the lines containing the 'port number' regex.
Lin_freak
It doesn't delete anything. It reads `file.txt` and for every line that matches `/^port$/` prints the next line, just like you asked.
jamessan
@jamessan: No, your regex is too restrictive. Your `sed` command is likely to not print anything at all based on the OP's example data.
Dennis Williamson
A: 

Give this a try:

sed -n '/Port Number/{n;p}' file.txt

In GNU sed case insensitive:

sed -n '/Port Number/I{n;p}' file.txt
Dennis Williamson
Is n the number of lines to display? And what is p?
Lin_freak
`n` is the `sed` command to read the next line. `p` is the `sed` command to print the line (since `-n` tells it not to print lines by default).
Dennis Williamson
A: 

use awk. Its simpler to understand than sed.

awk '/port number/{getline;print }' file

'getline' gets the next line after /port number/ is matched.

ghostdog74