これは、その仕事をするPerlのほとんど些細なことです。
#!/usr/bin/env perl
#
# Substitute environment variables into text
use strict;
use warnings;
while (<>)
{
while (m/\${(\w+)}/g)
{
my $env = $1;
if (defined $ENV{$env})
{
my $sub = $ENV{$env};
s/\${$env}/$sub/g;
}
}
print;
}
環境変数が定義されていない場合、${VARIABLE}
表記は変更されません。
たとえば、入力データについて:
This is ${HOME} and so is this (${HOME}) and that's ${USER} and that's all.
This is ${UNDEFINED} and that is ${UNDEF} too.
出力は次のようになります。
This is /work4/jleffler and so is this (/work4/jleffler) and that's jleffler and that's all.
This is ${UNDEFINED} and that is ${UNDEF} too.
<>
Perlはおそらくそれほどコンパクトではありませんが、読み取り演算子と一致、置換、および印刷演算子がデフォルト変数で機能することがわかっていれば、多かれ少なかれ理解できます$_
。
RHEL 5Linux(質問しないでください)でPerl 5.12.1(自家製)を使用して、私は以下を使用しました:
$ cat x3
This is ${UNDEFINED} and that is ${UNDEF} too.
This is ${HOME} and so is this (${HOME}) and that's ${USER} and that's all.
$ perl subenv.pl x3
This is ${UNDEFINED} and that is ${UNDEF} too.
This is /work4/jleffler and so is this (/work4/jleffler) and that's jleffler and that's all.
$
ヒアドキュメントを使用してテンプレートを作成する場合は注意が必要です。シェルはそれらの変数も拡張します。
/usr/bin/perl
また、RHELマシンでPerl 5.8.8が見つかり、同じ出力が生成されました。Mac OS X10.7.5でPerl5.16.0もチェックし、対応する結果(別のホームディレクトリ)を確認しました。${USER}
また、環境に設定されていないHP-UX11.00マシンでPerl5.6.1を見つけましたが、${HOME}
正しく置き換えられました。