Lin_freak
Lin_freak

Reputation: 21

Next line matching the regex in bash

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?

Upvotes: 2

Views: 2108

Answers (3)

ghostdog74
ghostdog74

Reputation: 342323

use awk. Its simpler to understand than sed.

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

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

Upvotes: 3

jamessan
jamessan

Reputation: 42657

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.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 359965

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

Upvotes: 0

Related Questions