从字符串中提取带有sed和awk的所有IP地址 [英] Extract all ip addresses with sed and awk from a string
本文介绍了从字符串中提取带有sed和awk的所有IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用grep从字符串中提取所有IP地址很简单.
It is simple to extract all ip addresses with grep from a string.
string="221.11.165.237xxxx221.11.165.233\n
219.158.9.97ttttt219.158.19.137"
echo $string |grep -oP "(\d+\.){3}\d+"
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137
regrex模式很简单(\d+\.){3}\d+
.
使用sed和awk执行相同的工作.
对于sed:
The regrex pattern is simple (\d+\.){3}\d+
.
Do the same job with sed and awk.
For sed:
echo $string | sed 's/^\(\(\d\+\.\)\{3\}\d\+\)$/\1/g'
221.11.165.237xxxx221.11.165.233\n 219.158.9.97ttttt219.158.19.137
对于awk:
echo $string |gawk 'match($0,/(\d+\.){3}\d+/,k){print k}'
echo $string |awk '/(\d+\.){3}\d+/{print}'
如何修复sed和gawk(awk)?
预期输出与grep相同.
How to fix it for sed and gawk(awk)?
The expect output is the same as grep.
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137
推荐答案
这可能对您有用(GNU sed):
This might work for you (GNU sed):
sed '/\n/!s/[0-9.]\+/\n&\n/;/^\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\n/P;D' file
在仅由数字和句点组成的字符串的两侧插入换行符.如果一行仅包含IP地址,则将其打印出来.
Insert newlines either side of strings consisting only of numbers and periods. If a line contains only an IP address print it.
使用-r
选项可以更轻松地呈现内容:
An easier-on-the-eye rendition uses the -r
option:
sed -r '/\n/!s/[0-9.]+/\n&\n/;/^([0-9]{1,3}\.){3}[0-9]{1,3}\n/P;D' <<<"$string"
这篇关于从字符串中提取带有sed和awk的所有IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文