AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79244484
Accepted
M.E.
M.E.
Asked: 2024-12-02 22:40:46 +0800 CST2024-12-02 22:40:46 +0800 CST 2024-12-02 22:40:46 +0800 CST

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

  • 772

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

{{env MYVAR}} 
{{env PATH}} 
{{env DISPLAY}} 

与环境变量 MYVAR、PATH、DISPLAY 等的内容相关。

我的目标是不向该脚本传递任何参数,因此它将自动检测模式并用环境变量{{env VARNAME}}的值替换。$VARNAME

该脚本通过标准输入获取输入并通过标准输出提供输出。

通过标准输入的示例输入文本:

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}} and the path is {{env PATH}}.

通过标准输出的预期输出:

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 and the path is /bin;/usr/bin;/usr/local/bin.

我已尝试过:

到目前为止,我只设法通过命令行传递一个变量来完成此操作。

#!/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;
}'

因此,上述方法有效,但需要你做./parsing_script MYVAR

我想避免将环境变量指定为命令行参数。

架构/操作系统

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

笔记

如果 awk 不是合适的工具,我愿意听取解决方案(请不要使用 Python 或 Perl)。

bash
  • 5 5 个回答
  • 96 Views

5 个回答

  • Voted
  1. markp-fuso
    2024-12-02T23:57:09+08:002024-12-02T23:57:09+08:00

    假设:

    • env字符串和变量名之间只有一个空格
    • 对于未定义的变量,我们将保留{{env UNDEFINED_VARIABLE}}字符串

    示例输入文件:

    $ cat sample.dat
    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}} and the custom var MYVAR={{env MYVAR}}.
    Handling missing variable DOESNOTEXIST={{env DOESNOTEXIST}} and empty var EMPTY_VAR={{env EMPTY_VAR}}.
    

    awk在尝试替换之前验证环境变量是否存在的一个想法:

    $ cat parsing_script
    #!/bin/bash
    
    export DISPLAY=":0.2"
    export MYVAR="something_like_this"
    export EMPTY_VAR=""
    
    awk '
    { line = $0
      out  = ""
      while (match(line,/{{env [^}]+}}/)) {
            var = substr(line,RSTART+6,RLENGTH-6-2)
            if (var in ENVIRON)                                 # is this a valid variable?
               out = out substr(line,1,RSTART-1) ENVIRON[var]
            else
               out = out substr(line,1,RSTART+RLENGTH-1)
            line = substr(line,RSTART+RLENGTH)
      }
      print out line
    }
    ' "${@:--}"                                                 # allow for reading from explicit file or stdin
    

    进行试驾:

    ########
    # read from stdin
    
    cat sample.dat | ./parsing_script
    
    ########
    # read from explicit file reference
    
    ./parsing_script sample.dat
    

    这些都产生:

    This is a basic templating system that can replace environment variables in regular text files.
    For example the DISPLAY in this system is :0.2 and the custom var MYVAR=something_like_this.
    Handling missing variable DOESNOTEXIST={{env DOESNOTEXIST}} and empty var EMPTY_VAR=.
    
    • 4
  2. anubhava
    2024-12-02T23:13:01+08:002024-12-02T23:13:01+08:00

    你可以使用这个awk解决方案:

    awk 'NF {
       while (match($0, /\{\{env [_[:alnum:]]+}}/)) {
          $0 = substr($0, 1, RSTART-1) ENVIRON[substr($0, RSTART+6, RLENGTH-8)] substr($0, RSTART+RLENGTH)
       }
    }
    1' file
    
    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 and the path is /bin;/usr/bin;/usr/local/bin.
    

    如果您正在使用gnu awk,则可以通过在函数中使用捕获组match参数进一步简化它:

    awk 'NF {
       while (match($0, /{{env[[:blank:]]+([_[:alnum:]]+)}}/, m)) {
          $0 = substr($0, 1, RSTART-1) ENVIRON[m[1]] substr($0, RSTART+RLENGTH)
       }
    }
    1' file
    
    • 3
  3. Best Answer
    Renaud Pacalet
    2024-12-02T22:48:18+08:002024-12-02T22:48:18+08:00

    以下内容适用于任何 POSIX awk。请注意,它以递归方式执行替换。如果环境变量A={{env B}}和环境变量B=bar,则将{{env A}}替换为bar。

    它使用正则表达式,[{][{]env[[:space:]]+[A-Za-z_][A-Za-z0-9_]*[}][}]因为有效的 shell 变量名是仅由字母数字字符和下划线组成,并以字母或下划线开头的单词。因此,它不会替换{{env 98FOO}}。

    {{env和变量名之间的空格可以是制表符和空格的任意混合。

    #!/bin/sh
    
    cat - | awk '
    BEGIN { re = "[{][{]env[[:space:]]+[A-Za-z_][A-Za-z0-9_]*[}][}]" }
    $0 ~ re {
      s = $0
      while(match(s, re)) {
        v = substr(s, RSTART + 6, RLENGTH - 8)
        sub(/^[[:space:]]+/, "", v)
        s = substr(s, 1, RSTART - 1) ENVIRON[v] substr(s, RSTART + RLENGTH)
      }
      print s
      next
    }
    1'
    

    正如评论中提到的,递归替换可能会导致无限循环(例如A='{{env A}}')。只有一次替换的版本可能类似于:

    BEGIN { re = "[{][{]env[[:space:]]+[A-Za-z_][A-Za-z0-9_]*[}][}]" }
    $0 ~ re {
      s = $0
      while(match(s, re)) {
        v = substr(s, RSTART + 6, RLENGTH - 8)
        sub(/^[[:space:]]+/, "", v)
        printf("%s%s", substr(s, 1, RSTART - 1), ENVIRON[v])
        s = substr(s, RSTART + RLENGTH)
      }
      print s
      next
    }
    1' input
    

    但当然,有了A='{{env B}}'和B=bar,{{env A}}就会变成{{env B}},而不是bar。

    • 2
  4. Cyrus
    2024-12-03T02:54:39+08:002024-12-03T02:54:39+08:00
    export PATH='/bin:/usr/bin:/usr/local/bin'
    export DISPLAY=':0.0'
    cat file | sed 's/{{env \([^ ]\+\)}}/${\1}/g' | envsubst
    

    输出:

    这是一个基本的模板系统,可以替换常规文本文件中的环境变量。
    例如本系统中的DISPLAY为:0.0,路径为/bin:/usr/bin:/usr/local/bin。
    

    看:man envsubst

    • 2
  5. Ed Morton
    2024-12-03T08:48:17+08:002024-12-03T08:48:17+08:00

    match()使用 GNU awk将3rg 参数设置为{在正则表达式的开头或后面不跟数字时的文​​字:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    awk '
        {
            head = ""
            tail = $0
            while ( match(tail, /({{env ([[:alpha:]_][[:alnum:]]*)}})(.*)/, a) ) {
                var  = a[2]
                head = head substr(tail,1,RSTART-1) (var in ENVIRON ? ENVIRON[var] : a[1])
                tail = a[3]
            }
            print head tail
        }
    ' "${@:--}"
    

    $ export DISPLAYX=':0.0'
    $ export PATHX='/bin;/usr/bin;/usr/local/bin'
    

    $ ./tst.sh file
    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 and the path is /bin;/usr/bin;/usr/local/bin.
    

    我正在缓慢地填充tail,head而不是不断地重新构造和重新评估,$0以避免重新评估以前替换的字符串,因此DISPLAY='{{env DISPLAY}}'不会导致无限循环。

    我在示例 shell 代码和示例输入中的变量名末尾放置了一个 X,因为我不想弄乱我的真实 DISPLAY 和 PATH。

    如果您使用的{{env FOO}}不是FOO环境变量,那么该文本将不会改变。

    • 0

相关问题

  • (macOS Bash) 2个看似相同的字符串并不相等,仅通过“set -x”显示差异

  • Xargs:尽管扩展了别名,但别名替换仍失败

  • Linux 环境中 $PATH 和 ${PATH:+:${PATH}} 的区别

  • awk 查找并替换为正则表达式和环境变量

  • 如何在 bash 中对任意长度的编号、分隔字母数字字符串的文件名进行零填充?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve