shell脚本如何修改文件的内容?

sh/bash/dash/ksh/zsh等Shell脚本
回复
chenxitwo
帖子: 31
注册时间: 2011-08-13 20:03

shell脚本如何修改文件的内容?

#1

帖子 chenxitwo » 2015-01-20 16:49

如题,具体问题请看下面:

脚本需要修改配置文件的内容。配置文件的内容如下:
WIFI_MODE=STA
IPADDRESS=192.168.15.133
NETMASK=255.255.255.0
...

配置文件名为setting.dat,脚本文件命令为update_setting.sh
应用举例:
实现将WIFI_MODE项改为AP,命令如下
./update_setting.sh setting.dat WIFI_MODE AP

我的code:
#!/bin/sh
# read setting file

dest_file=$1
dest_str=$2
dest_var=$3

#Find the replace line
line_num=`grep -n "$dest_str" "$dest_file" | cut -d ':' -f 1`
if [ $? -eq 0 ] ; then
cat $dest_file | sed "${line_num}c ${dest_str}=${dest_var}" > ${dest_file}_temp
mv ${dest_file}_temp ${dest_file}


但是我的脚本中有 重定向+产生临时文件,感觉不是很好,所以请教各位是否还有更好的方法。
头像
susbarbatus
帖子: 2966
注册时间: 2010-04-10 16:14
系统: Arch Linux

Re: shell脚本如何修改文件的内容?

#2

帖子 susbarbatus » 2015-01-20 19:30

sed 加 -i 选项
沉迷将棋中……
头像
susbarbatus
帖子: 2966
注册时间: 2010-04-10 16:14
系统: Arch Linux

Re: shell脚本如何修改文件的内容?

#3

帖子 susbarbatus » 2015-01-20 19:31

sed 前面的管道也可以去掉吧……
沉迷将棋中……
onlylove
论坛版主
帖子: 5371
注册时间: 2007-01-14 16:23

Re: shell脚本如何修改文件的内容?

#4

帖子 onlylove » 2015-01-20 21:11

sed咯
#include <stdio.h>
void main()
{
double world;
unsigned letter;
short stay;
long memories;
printf("I miss you.\n");
}
chenxitwo
帖子: 31
注册时间: 2011-08-13 20:03

Re: shell脚本如何修改文件的内容?

#5

帖子 chenxitwo » 2015-01-21 10:10

根据两位的建议,查了sed命令的用法,找到更简单的方法。
code如下,供后来者参考:
#!/bin/sh
# read setting file

dest_file=$1
dest_str=$2
dest_var=$3

sed -i "s/^${dest_str}=.*$/${dest_str}=${dest_var}/g" $dest_file

感谢 susbarbatus和onlylove的建议,谢谢!
perry_li
帖子: 1
注册时间: 2015-01-26 13:05
系统: Win7

Re: shell脚本如何修改文件的内容?

#6

帖子 perry_li » 2015-01-26 13:08

如果非必要用脚本,其实直接用sed命令就可以搞定,如果要用脚本,你最好加上判断参数是否为空,否则会出现问题。
回复