使用sed搜索和替换文件中的IP地址 [英] Using sed to search and replace an ip address in a file

查看:22
本文介绍了使用sed搜索和替换文件中的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直在尝试让它工作一段时间,但并没有真正得到它.基本上,我有一个 IP 地址每天或多或少变化的文件.该文件只包含一个 ip 地址,这是我试图用疯狂的 grepping 替换的地址,以找到我当前的内部 ip.

Been trying to get this working for a while and not really quite getting it. Basically, I have a file with an ip address that changes more or less on a daily basis. The file only contains one ip address and this is the one I'm trying to replace with my crazy grepping to find my current internal ip.

我有这个

#!/bin/sh

newip=$(ifconfig | grep 0xfff | grep -Eo '([0-9]{1,3}.){3}[0-9]{1,3}' | grep -v 255)

echo $newip
sed 's/*.*.*.*/"$newip"/g' log.txt > logmod.txt

但它不是匹配和替换.我不熟悉 sed,我也是 regexp 的初学者.

but it's not matching and replacing. I'm not familiar with sed and I am a beginner with regexps too.

任何帮助都会很棒!谢谢:)

Any help would be awesome! Thanks :)

推荐答案

如果您的 sed 版本支持扩展正则表达式(-r 选项),您可以这样做类似这样的东西(类似于您在 grep 语句中的内容).还要注意 $newip 在单引号之外,以允许 shell 替换它.

If your version of sed supports extended regular expressions (the -r option), you could do something like this (which is similar to what you have in your grep statement). Also note $newip is outside the single quotes to allow the shell to replace it.

sed -r 's/([0-9]{1,3}.){3}[0-9]{1,3}'/"$newip"/

顺便说一句,这个解决方案仍然匹配不代表 IP 地址的字符串.有关更复杂的解决方案,请参阅IP 地址下的本网站.

BTW this solution still matches strings that do not represent IP addresses. See this site under IP Adresses for more complex solutions.

这篇关于使用sed搜索和替换文件中的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆