扩展文件中的已知环境并保留其他内容 [英] Expanding known env vers in a file and leaving others
问题描述
我敢肯定有一种非常简单的方法可以做到这一点.我正在尝试获取一个包含一些环境变量的文件并将其展开,以便将已知的那些扩展为它们的值,而那些未被单独保留的值.
I'm sure there's a really easy way of doing this. I'm trying to take a file which contains some environment variables and expand it so that those which are known are expanded to their values whereas those which are not are left alone.
例如,如果我的文件包含以下内容:
For example, if my file contained the following:
${I_EXIST}
${I_ALSO_EXIST}
${I_DONT_EXIST}
这将扩展为:
existValue
alsoExistValue
${I_DONT_EXIST}
理想情况下,我想尽可能简单地做到这一点,所以我不想使用sed,awk或perl进行复杂的替换.我正在考虑类似于此处"文件的内容,但是除了我无法正确使用语法之外,它还会清空任何无法扩展的内容.例如:
I ideally want to do this as simply as possible so I don't want a complex substitution using sed, awk or perl. I'm thinking of something similar to a "Here" file, but apart from the fact that I can't get the syntax right, it also blanks out anything which does not expand. E.g:
cat <<EOF
> ${I_EXIST}
> ${I_ALSO_EXIST}
> ${I_DONT_EXIST}
EOF
existValue
alsoExistValue
(即最后一个值扩展为空)
(i.e. the last value expands to nothing)
更新
真的应该明确地表明,我正在考虑每行可能有多个替换.我确实找到了一种方法,如果我们不对文件中以 $ {MYVAR}
出现的变量大惊小怪,但也许 MYVAR
可以做到:
Should really have made clear that I was thinking about potentially more than one substitution per line. One way I did find to do this, if we're not fussed about the variables appearing in the file as ${MYVAR}
but maybe MYVAR
will do:
m4 $(env | sed's/\([A-Za-z0-9] * \)= \([[//A-Za-z_0-9:|%*.-@]* \)/-D \ 1 = \ 2')myfile
这使用M4预处理器替换环境中的所有对.这里有几个腔室:
This uses the M4 preprocessor to substitute all the pairs in your environment. A couple of caviats here:
- 对不起reg exp的东西.看起来很讨厌,我敢肯定有更好的表达方式.如果我的环境变量中有空格或集合中没有的任何不寻常字符,就会发现问题.
- 当然,这是一个钝器替换工具(我试图避免这种情况),因此当您不希望变量发生时,变量可能会被替换.
推荐答案
#!/bin/bash
while read a;
do
n=$(eval echo $a)
if [[ "$n" == "" ]]
then
echo $a
else
echo $n
fi
done < input
将此作为输入
${HOME}
${nonexistent}
给予
/home/myuser
${nonexistent}
这篇关于扩展文件中的已知环境并保留其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!