Linux 脚本编写 如何编写一个脚本,修改已有文件中的内容

ashaur 2011-09-25 09:21:20
如何编写一个脚本,修改已有文件中的内容

例如 /etc/resolv.conf 这个文件 里面的内容是nameserver 192.168.10.1 用来搜索域名
如果要写一个脚本怎样才能只修改IP

我试着用echo来写,但不是追加就是覆盖了
#!/bin/bash
echo 'nameserver 192.168.10.2' > /etc/resovl.conf

这样来写就全部改掉了,如果文件内容较多,但只想该其中的某些地方, 该如何写,请高手指教,不胜感激!!!!


就以DNS的数据库文件为例 /var/named 中的honey.com.zone (文件名随便起的)

$TTL 86400
@ IN SOA honey.com. root.honey.com.(
42 ; serial (d.adams)
3H ; refresh
1W ; retry
) ; monimum
@ IN NS nsl.honey.com.
www IN A 192.168.1.7


修改为
@ IN NS nsl.ashaur.com.
www IN A 192.168.1.6

...全文
3238 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
delphiwcdj 2011-10-01
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 qq120848369 的回复:]

引用 5 楼 dengxiayehu 的回复:

楼主解决了没,主要使用了sed -i来替换文本,当然这里还涉及到一个匹配IP地址的正则
表达式,十一闲得蛋疼,写了个,参考下:
Python code

#!/bin/bash
# filename: modi_ip.sh

# usage: modi_ip.sh <file2modi> <new-IP>
# eg: modi……
[/Quote]
简便
qq120848369 2011-10-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 dengxiayehu 的回复:]

楼主解决了没,主要使用了sed -i来替换文本,当然这里还涉及到一个匹配IP地址的正则
表达式,十一闲得蛋疼,写了个,参考下:
Python code

#!/bin/bash
# filename: modi_ip.sh

# usage: modi_ip.sh <file2modi> <new-IP>
# eg: modi_ip.sh honey.com.zone 192.168.1.……
[/Quote]

sed -i -r "s/([0-9]{1,3})\.\1\.\1\.\1}/$new_ip/g" $file2modi
_了凡_ 2011-10-01
  • 打赏
  • 举报
回复
楼主解决了没,主要使用了sed -i来替换文本,当然这里还涉及到一个匹配IP地址的正则
表达式,十一闲得蛋疼,写了个,参考下:

#!/bin/bash
# filename: modi_ip.sh

# usage: modi_ip.sh <file2modi> <new-IP>
# eg: modi_ip.sh honey.com.zone 192.168.1.6

if [ $# -ne 2 ]; then
echo "usage: modi_ip.sh <file2modi> <new-IP>" >&2
exit 1
fi

file2modi=$1
new_ip=$2
sed -i "s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/$new_ip/g" $file2modi
exit 0

看原始文件:
xxx$ cat honey.com.zone
@ IN SOA honey.com. root.honey.com.(
42 ; serial (d.adams)
3H ; refresh
1W ; retry
) ; monimum
@ IN NS nsl.honey.com.
www IN A 192.168.1.7

执行下,然或再查看:
xxx$ modi_ip.sh honey.com.zone 192.168.1.6
xxx$ cat honey.com.zone
@ IN SOA honey.com. root.honey.com.(
42 ; serial (d.adams)
3H ; refresh
1W ; retry
) ; monimum
@ IN NS nsl.honey.com.
www IN A 192.168.1.6
once_and_again 2011-09-28
  • 打赏
  • 举报
回复
sed -i 's/src/des/' filenmae
ashaur 2011-09-26
  • 打赏
  • 举报
回复
您好,对这个命令不熟悉,您能不能写的具体一点 把整个语句都写出来!!谢谢了!!
wangtingguang 2011-09-25
  • 打赏
  • 举报
回复
sed -i 's#修改前#修改后#' 文件名
wangtingguang 2011-09-25
  • 打赏
  • 举报
回复
sed

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧