如何从文本中提取出所有的IP地址,分别以shell、python方式写出
Shell示例:
#!/bin/bash
text="Here is a sample text with IP addresses 192.168.1.1 and 10.0.0.1."
# 使用grep命令和正则表达式提取IP地址
ips=$(echo $text | grep -E -o "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
# 输出结果
for ip in $ips
do
echo $ip
done
输出结果为:
192.168.1.1
10.0.0.1
Python示例:
import re
text = "Here is a sample text with IP addresses 192.168.1.1 and 10.0.0.1."
# 正则表达式
regex = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
# 获取匹配结果
matches = re.findall(regex, text)
# 输出结果
for match in matches:
print(match)
输出结果为:
192.168.1.1
10.0.0.1
这两个示例都使用正则表达式来匹配IP地址,其中Shell示例使用grep命令,Python示例使用re模块的findall函数。

浙公网安备 33010602011771号