简体   繁体   English

使用循环和sed Bash脚本在不同目录中的文件中设置变量值

[英]Setting Variables Value in a File in Different Directory Using Loops and sed Bash Script

I'm trying to write a bash script that will check five variable values in a file in a different directory and update them accordingly. 我正在尝试编写一个bash脚本,该脚本将检查不同目录中文件中的五个变量值并相应地更新它们。 Since there is five variables, I was thinking to do it in a for loop, but I don't know how to compare these values. 由于有五个变量,因此我想在for循环中执行此操作,但我不知道如何比较这些值。 What I'd like to have is pseudo code: 我想拥有的是伪代码:

var_f=(server_name app_name metadata1 metadata2 metadata)  #the variable name in file
var_v=(server1 app /tmp/2 tmp/3 /tmp/config.xml
for i in "${var_f[@]}"
do
   if var_f(i)~=var_v(i)
            sed -i -e 's/server_name=RANDOM_VAL/server_name=server1/g'   server.properties
    else
         then do nothing   
    fi
 done    

The code I've so far: 我到目前为止的代码:

#!/bin/bash

cd '/home/me/'
set -- $(<server.properties)
echo $server_name # jsut to see if set command is working
sed -i -e 's@server_name=@server_name=server1@g' server.properties
sed -i -e 's@app_name=@app_name=app@g' server.properties
sed -i -e 's@metadata1=@metadata1=/tmp/2@g' server.properties
sed -i -e 's@meatadata2=@metadata2=/tmp/3@g server.properties
sed -i -e 's@metadata=@metadata=/config.xml@g' server.properties
cd '/home/my/test/'

How can I run through var_f and var_v and compare the two? 如何遍历var_f和var_v并比较两者? the value of var_f from the file is obtainable using the --set command, but I don't know how to compare it to the correct values (var_v). 使用--set命令可以从文件中获取var_f的值,但我不知道如何将其与正确的值(var_v)进行比较。 Also, var_v are the correct values that will replace the wrong ones using the for loop and if statement. 同样,var_v是正确的值,它将使用for循环和if语句替换错误的值。

Any help will be very appreciated. 任何帮助将不胜感激。 Thank you. 谢谢。

I think it advisable to update all variables in a single sed run. 我认为最好在一次sed运行中更新所有变量。

#!/bin/bash
var_f=(server_name app_name metadata1 metadata2 metadata) #variable name
var_v=(server1 app /tmp/2 /tmp/3 /tmp/config.xml)
for (( i=0; i < ${#var_f[*]}; ++i ))
do
    substitutions+="s@${var_f[$i]}=\S*@${var_f[$i]}=${var_v[$i]}@;"
done
sed -i "$substitutions" /home/me/server.properties

Are you seriously bothered by the file being rewritten every time the script runs? 您是否对每次运行脚本时都要重写的文件感到严重困扰? Presumably comparing the current values to the correct ones would take longer. 大概将当前值与正确的值进行比较将花费更长的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM