如何使用 awk 用环境变量替换模式?

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

我正在尝试编写一个简单的脚本,它将通过标准输入接收文本,并按原样输出所有内容,除了它将替换遵循此模式的事件:

{{env MYVAR}} {{环境路径}} {{env 显示}}

与环境变量MYVAR、PATH、DISPLAY等内容

输入文本示例:

This is a basic templating system that can replace environment variables in regular text files.
For example the DISPLAY in this system is {{env DISPLAY}}.

预期输出:

This is a basic templating system that can replace environment variables in regular text files.
For example the DISPLAY in this system is :0.0.

我尝试过的:

到目前为止,我只能通过命令行传递一个变量来完成它。

#!/bin/sh

# Check if the first argument is set
if [ -z "$1" ]; then
    echo "No variable name provided." >&2
    exit 1
fi

VARIABLE_NAME="$1"

# Use awk to replace '{{env VARIABLE_NAME}}' with the value of the environment variable
awk -v var_name="$VARIABLE_NAME" '
function escape(s) {
    esc = "";
    for (i = 1; i <= length(s); i++) {
        c = substr(s, i, 1);
        if (c ~ /[.[\]$()*+?^{|\\{}]/) {
            esc = esc "\\" c;
        } else {
            esc = esc c;
        }
    }
    return esc;
}
BEGIN {
    search = "{{env " var_name "}}";
    search_esc = escape(search);
    replacement = ENVIRON[var_name];
}
{
    gsub(search_esc, replacement);
    print;
}'

架构/操作系统

我正在使用 FreeBSD 的 awk 及其 POSIX shell /bin/sh

bash awk sh freebsd
1个回答
0
投票

您可以传递以空格分隔的名称列表,并在

split
语句中使用函数
BEGIN
将其转换为数组:

awk -v var_names="$@" '
  BEGIN {
    n = split(var_names, arr)
  }
  {
    for(i=1; i<=n; i++) {
      v=arr[i]
      gsub(escape("{{ env " v "}}"), ENVIRON[v])
    }
  }'
© www.soinside.com 2019 - 2024. All rights reserved.