Bash grep ip从行 [英] Bash grep ip from line
问题描述
我有文件ip.txt,其中包含以下内容
I have the file ip.txt which contain the following
ata001dcfe16f85.mm.ph.ph.cox.net (24.252.231.220)
220.231.252.24.xxx.com (24.252.231.220)
我做了这个bash命令来提取ips:
and I made this bash command to extract ips :
grep -Eo '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' ip.txt | sort -u > good.txt
我想编辑代码,以便仅提取括号之间的ips.不是所有的ip都在线,因为当前代码提取了ip 220.231.252.24
I want to edit the code so it extracts the ips between the parentheses ONLY . not all the ips on the line because the current code extract the ip 220.231.252.24
推荐答案
要使IP处于括号内,您所需要做的就是将整个正则表达式包装在转义的\( \)
To get the IP within paranthesis all you need is to wrap the entire regex in an escaped \( \)
grep -Eo '\((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\)'
将输出为
(24.252.231.220)
(24.252.231.220)
如果您还希望在输出中摆脱偏执狂,环顾四周会很有用
if you want to get rid of the paranthesis as well in the output, look around would be usefull
grep -oP '(?<=\()(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?=\))'
将产生的输出为
24.252.231.220
24.252.231.220
一个更轻巧的版本
grep -oP '(?<=\()(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}(?=\))'
此处
[0-9]{2}
匹配数字2次
(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}
匹配.
,后跟三位3位数
(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}
matches .
followed by 3 digit number three times
可以使用到uniq
的管道将重复行删除为
The repeating lines can be removed using a pipe to uniq
as
grep -oP '(?<=\()(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}(?=\))' input | uniq
将输出赋予为
24.252.231.220
这篇关于Bash grep ip从行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!