SED用文件内容替换字符串

时间:2018-02-05 22:36:05

标签: linux unix

我有环境变量的文件。

带有e.variables的文件包含以下内容:

STACK=OVERFLOW
PORT=3000 

我的.txt文件包含以下内容:

First variable: STACK 
Second variable: PORT 

我想使用带有环境变量的文件中的值替换我的.txt文件中的STACKPORT

结果:

First variable: OVERFLOW
Second variable: 3000

我尝试使用SED,但没有成功。

sed -i -e 's/STACK/????/g' .txt

1 个答案:

答案 0 :(得分:2)

如果file1中的变量是导出,则可以执行此操作,这需要s/pattern/replacement/e命令的GNU sed

$ cat file1
export STACK=OVERFLOW
export PORT=3000

$ cat file2
First variable: STACK
Second variable: PORT

$ . file1

$ sed -i.bak -r 's/^([^:]+: *)(.+)/printf "%s%s\\n" "\1" "$\2"/e' file2

$ cat file2
First variable: OVERFLOW
Second variable: 3000
相关问题