使用sed根据变量值注释掉文件中相匹配的记录行

 

问题描述

有批量的profile文件需要更新,因为其中某些环境变量的值需要更新,于是利用sed命令写了如下函数,方便以后使用。

代码展示

unset -f add_var_to_file
function add_var_to_file(){
env_var=$1
new_value=$2
tgt_file=$3
# comment out old env lines
sed -e "/ $env_var/ s/^#*/#/" -i $tgt_file;
# add new env variable line
curr_time=`date +"%Y-%m-%d %H:%M:%S"`;
echo "">> $tgt_file
echo "# updated at $curr_time" >> $tgt_file;
echo "export $env_var=$new_value;" >>$tgt_file;
}

posted @ 2019-03-13 20:35  LestatZ  阅读(584)  评论(0编辑  收藏  举报