开发者

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?


use awk. Its simpler to understand than sed.

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

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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜