${}の値を変更するには、awk / sedが必要です。

${}の値を変更するには、awk / sedが必要です。

env.propertiesファイルから値を取得してURLをテストしようとしています。

たとえば、私のenv.propertiesは次のようになります。

a.host.name=wanx.com
b.host.name=xyu.com
c.host.name=${b.host.name}
d.host.name=${c.host.name}

url1=https://${d.host.name}/test
url2=https://${a.host.name}/test2

これまでに行った作業 - 1.ファイルに「.」があるため、直接置き換えることはできません。だから私はawkを使って点を下線に変えました。

awk -F= -vOFS="=" 'gsub(/\./,"_",$1)+1' endpoint_test.txt

今私のファイルは以下のようになります -

a_host_name=wanx.com
b_host_name=xyu.com
c_host_name=${b.host.name}
d_host_name=${c.host.name}

url1=https://${d.host.name}/test
url2=https://${a.host.name}/test2
  1. ${b.host.name}と${c.host.name}の値を変更しようとしましたが、Googleで見つけたawkコマンドのほとんどを試しました。以下は私が試したコマンドです

    awk -F= -vOFS="${#*}" 'gsub(/\./,"_",$1)+1' endpoint_test2.txt

    awk -F\" '{OFS="\""; for (i = 2; i < NF; i += 2) gsub(/[$,]/,"",$i); gsub(/"/,""); print}' endpoint_test2.txt

しかし、これはうまくいきません。 ${value}の点を下線に変更したいと思います。したがって、これをシェルに移すと簡単に交換できます。

編集#1 -

最終的には、次の出力ファイルが必要です。

a_host_name=wanx.com
b_host_name=xyu.com
c_host_name=${b.host.name}
d_host_name=${c.host.name}

url1=https://${d_host_name}/test
url2=https://${a_host_name}/test2

したがって、このファイルをシェルに変換することでこれを行います。

a_host_name=wanx.com
b_host_name=xyu.com
c_host_name=${b_host_name}
d_host_name=${c_host_name}

url1=https://${d_host_name}/test
url2=https://${a_host_name}/test2

echo $url1
echo $url2

このファイルの出力 -

https://xyu.com/test
https://wanx.com/test2

編集#2 - bashを自分で試しましたが、$ {}の値を変更する必要があるため、間違った置換と言いました。

編集#3 -

私が試しているオペレーティングシステムはAIXにあり、ファイルに "a.host.name"と同じ変数が含まれていない可能性があります。 「a.name.host」などの変数も含めることができます。たとえば、ファイルは次のようになります。

a.b.host=qwel.wanx.net
b.host.name=ioy.xyu.net
c.xcv.host=poiu.deolite.net
d.host.name=${b.host.name}
e.host.name=${c.host.name}

abcv.stub.url=https://${d.host.name}/test
xcm.stub.url=https://${a.b.host}/test2

このコマンドを使用すると、編集#3で言及された極端なケースを達成することができました。

perl -pe 's/^[\w.]+(?==)|\$\{[\w.]+\}/ $_ = $&; tr|.|_|; $_ /ge' file

今私の出力は次のようになります。

a_b_host=qwel.wanx.net
b_host_name=ioy.xyu.net
c_xcv_host=poiu.deolite.net
d_host_name=${b_host_name}
e_host_name=${c_host_name}

abcv_stub_url=https://${d_host_name}/test
xcm_stub_url=https://${a_b_host}/test2

最後に、URLを次のように別々のファイルに入れる必要があります。

https://ioy.xyu.net/test
https://qwel.wanx.net/test2

ベストアンサー1

次のことができます。

perl -pe 's/^[\w.]+(?==)|\$\{[\w.]+\}/$& =~ y|.|_|r/ge' < file

つまり、は単語の文字シーケンス.で置き換えられるか、または後に続く行の先頭にあるまたは内部で置き換えられます。_.=${...}

r演算子のフラグ(y///代替結果が変数に適用されずに返されるようにする)には、perl 5.14以降が必要です。以前のバージョンでは、いつでも次のことができます。

perl -pe 's/^[\w.]+(?==)|\$\{[\w.]+\}/$_ = $&; y|.|_|; $_/ge' < file

perl今、最後の作業のためにここですべてのことを行うことは、シェルのコードを解釈するのと同じくらい簡単で、これは非常に危険です。

 perl -lne '
    s/\$\{([\w.]+)\}/$v{$1}/g;
    if (/^([\w.]+)=(.*)/) {
      $v{$1} = $v = $2;
      print $v if $1 =~ /_url$/
    }' < file > separate-file

おすすめ記事