shell脚本在java中传递值属性文件

问题描述 投票:0回答:1

我有一个如下所示的属性文件:

mysql.username=USERNAME
mysql.pass=PASS

我需要使用传递给shell脚本的变量值来更改USERNAMEPASS。我不能使用sed,因为第一次使用“值”替换USERNAME和PASS时工作正常但是一旦被替换,sed将不会在脚本第二次运行时在文件中找到变量名,因此是一个问题。

怎么办呢?

bash shell sh
1个回答
0
投票

我相信实现目标的最简单方法是始终在未触摸的模板文件上执行替换,而不是尝试处理生成的文件的先前版本:

# produce a first version of the file.properties 
sed -e 's/USERNAME/user1/' -e 's/PASS/pass1/' file.properties.template > file.properties

# succesfully produce a second version of the file.properties
sed -e 's/USERNAME/user2/' -e 's/PASS/pass2/' file.properties.template > file.properties

另一种方法是更改​​脚本的输入(或代码?),以便您的搜索和替换操作不是基于占位符值,而是基于属性名称:

$ cat test.sh
#!/bin/bash

target=$1
shift

while key=$1 && value=$2 && shift 2; do
    sed -i "s/^$key=.*/$key=$value/" $target
done

$ cat test.props
mysql.hostname=HOSTNAME
mysql.username=USERNAME
mysql.pass=PASS

$ ./test.sh test.props mysql.username sa mysql.pass clearTextPasswordsAreTerrible

$ cat test.props
mysql.hostname=HOSTNAME
mysql.username=sa
mysql.pass=clearTextPasswordsAreTerrible

$ ./test.sh test.props mysql.username secondTry mysql.pass successfullyModified

$ cat test.props
mysql.hostname=HOSTNAME
mysql.username=secondTry
mysql.pass=successfullyModified
© www.soinside.com 2019 - 2024. All rights reserved.