envsubst基于字符串 [英] envsubst based on string

查看:1582
本文介绍了envsubst基于字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件中有以下两行

  $ MyEnv 
someText $ MyEnv

我想使用envsubst来替换第二次出现的MyEnv变量。如何使用字符串someText来区分变量的第一个和第二个出现位置并替换为env变量?



so envsubst< ; file1> file2

 文件2 
$ MyEnv
someTextValueofMyEnv

这可能如何

解决方案

以下代码将替换输入第二行的所有环境变量。请求的 envsubst 命令是唯一使用的非内置文件。

  L = 0 
线; do
L = $((L + 1))
如果[$ L = 2];那么
echo$ line| envsubst
else
echo$ line
fi
done< file1> file2

开始阅读最后一行,因为它决定了输入和输出;逐行阅读 file1 的内容,为的每次迭代填充 $ line 循环。 echo 行被管道输入 file2



我们有一个行计数器 $ L 在循环开始时增加。如果我们在第2行,我们通过 envsubst 发送该行。否则,我们只是报告。





您还问过如何使用字符串someText 区分事件。我不太清楚你的意思,但是请考虑一下:

  while read line; do 
#$ line包含字符串'someText $ MyEnv'
#(字面上:$ line在删除该字符串时不匹配)
如果[$ line!=$ {行#* someText\ $ MyEnv}];那么
echo$ line| envsubst
else
echo$ line
fi
done< file1> file2

 



注意: code> envsubst 只会替换导出的变量。 envsubst 命令不可移植;它是 GNU gettext 的一部分),而不是部分 POSIX标准实用程序 Linux Standard Base命令(LSB)。 p>

要完全移植(并使用sh内置函数!),您需要使用 eval ,这是不安全的没有大量额外的支票。


I have the following two lines in my text file

$MyEnv
someText$MyEnv

I want to use envsubst to only replace the second occurence of MyEnv variable. How can I use the string "someText" to distinguish between the first and second occurrence of the variable and substitute in env variable?

so envsubst < file1 >file2

file 2
$MyEnv
someTextValueofMyEnv

How is this possible

解决方案

The following code will substitute all environment variables on the second line of the input. The requested envsubst command is the only non-builtin that is used.

L=0
while read line; do
  L=$((L+1))
  if [ $L = 2 ]; then
    echo "$line" |envsubst
  else
    echo "$line"
  fi
done < file1 > file2

Start reading with the last line since it dictates the inputs and outputs; the contents of file1 are read line by line, populating $line for each iteration of the while loop. The echo lines are piped into file2.

We have a line counter $L which increments at the beginning of the loop. If we're on line 2, we send the line through envsubst. Otherwise, we just report it.

 

You also asked how you could use the string "someText" to distinguish between occurrences. I'm not exactly sure what you mean by this, but consider this:

while read line; do
  # $line contains the string 'someText$MyEnv'
  # (literally: $line does not match itself when removing that string)
  if [ "$line" != "${line#*someText\$MyEnv}" ]; then
    echo "$line" |envsubst
  else
    echo "$line"
  fi
done < file1 > file2

 

Note: envsubst will only substitute exported variables. The envsubst command is not portable; it's part of GNU gettext) and it is not a part of either the POSIX standard utilities or the Linux Standard Base commands (LSB).

To be fully portable (and fully using sh builtins!), you'd need to use eval, which is unsafe without lots of extra checks.

这篇关于envsubst基于字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆