linux - 使用 shell 脚本替换文件中的标记

标签 linux bash shell awk sed

我有一个包含 token 变量的文件。当我们切换环境时,我们希望为我们所在的环境正确替换这些 token 。

如何在 Linux shell 中执行此操作?我在考虑 awk 或 sed。

例子:

文件有这个数据:

DB_HOST=__HOST__
DB_PASSWORD=__PASSWORD__

我想读取这个文件,识别__HOST__并用环境变量$(HOST)替换它。我们将从两个下划线之间的匹配字符串中获取环境变量名称。

有谁知道我们如何做到这一点?

最佳答案

envsubst 程序大致就是为此目的而设计的,但它希望使用标准的 shell 格式来替换环境中的字符串:

# Here-doc delimiter quoted to avoid having the shell do the substitutions
$ HOST=myhost PASSWORD=secret envsubst <<"EOF"
DB_HOST=$HOST
DB_PASSWORD=${PASSWORD}
EOF

DB_HOST=myhost
DB_PASSWORD=secret

envsubst 是 Gnu gettext 的一部分,可广泛使用。如果你真的需要使用 __...__ 语法,很容易通过 sed 将其更改为 envsubst 语法:

$ cat myfile.txt
DB_HOST=__HOST__
DB_PASSWORD=__PASSWORD__

$ sed -E 's/__(([^_]|_[^_])*)__/${\1}/g' myfile.txt |envsubst

或者,如果您有 Python,则有一个非常简单的解决方案:

from sys import stdin
from os import getenv
import re

pattern = re.compile(r"__(\w*)__")

def replacer(m):
    val = getenv(m[1])
    if val is None:
        # No such environment
        # Perhaps produce a warning, or an error
        # Here we just pass through the string unaltered
        return m[0]
    return val

print(pattern.sub(replacer, stdin.read()))

例子:

$ export HOST=myhost PASSWORD=secret 
$ python3 subst.py < myfile.txt
DB_HOST=myhost
DB_PASSWORD=secret

这个解决方案的关键是 Python(不幸的是,只有少数其他语言)允许模式替换的替换参数是一个函数,然后在每个连续的匹配项上调用它来生成替换文本。这使得在 Python 中编写这样的函数比在 awk 中更容易,例如,替换文本是固定的。

关于linux - 使用 shell 脚本替换文件中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768918/

相关文章:

linux - 如何使用 curl 命令行工具发布 LF?

linux - 如何找出程序在哪里寻找库

xml - Sed 替换保留前导空格

bash - shell脚本中的性能问题

python - Django 从 celery 的 subprocess.Popen 获得干净的返回

linux - 使用 crontab 在 @reboot 上运行 "screen -S name ./script"命令

linux - 通过脚本设置永久路径

linux - 用于检查进程并在未找到时重新启动程序的脚本

php - 无法执行包含来自php文件的docker命令的bash脚本

xcode - 将脚本文件添加到 Xcode 存档