SED$ で始まる正確な単語の検索と置換

SED$ で始まる正確な単語の検索と置換

私のPHPファイルには、$ downtime_hostsを使用して定義されたいくつかの変数があります。必要なのは、 $downtime_hosts = 8;ファイル内で何度も使用される$downtime_hosts = 15;他の変数に影響を与えずに変数全体を検索して置き換えるコマンドです。$downtime_hosts

ここで私の数字8,15,16はいつでも変更される可能性があります。必要なのは、$ downtime_hosts = newintegerで始まる行を見つけて、新しい行を$downtime_hosts = anyinteger$ downtime_hosts = newintegerに置き換えることです。参考にするかanyinteger / newinteger=2,3,4,15何でも

$downtime_hosts = 8;

$total_hosts = $all_hosts - $downtime_hosts;

if ($host_up == $total_hosts )

Hosts under downtime $downtime_hosts `

どんな意見でも大歓迎です!

ベストアンサー1

sed 's/$downtime_hosts = 8;/$downtime_hosts = 15;/' file.php

$パターンの最後に見つからない限りアンカーとして機能しないため、問題は発生しません。スクリプトsedは一重引用符で囲む必要があります。それ以外の場合、シェルは$downtime_hostsシェル変数に拡張しようとします。

行の先頭のパターンのみが一致します。

sed 's/^$downtime_hosts = 8;/$downtime_hosts = 15;/' file.php

整数8が任意の整数である場合:

sed 's/^$downtime_hosts = [0-9]*;/$downtime_hosts = 15;/' file.php

整数をシェル変数が保持する整数に置き換えるには、次のようにします$newint

sed "s/^\$downtime_hosts = [0-9]*;/\$downtime_hosts = $newint;/" file.php

シェルが変数をsed拡張するには、編集スクリプトの周りに二重引用符を使用する必要があります。$newintこれはまた、私たちが2つの既存のシェルから逃げる必要があることを意味します$

おすすめ記事