特定のコンテキストでファイル内の値を操作結果に置き換える

特定のコンテキストでファイル内の値を操作結果に置き換える

ローカル URL と速度パラメータを含む JSON オブジェクトの配列があり、[{server:"192.168.0.100", speed:34}, {server:"192.168.0.130", speed:52},...]
各サーバーの速度値を更新する必要があります。

次のようなリンクを読む   文字列が特定のコンテキストで見つかった場合のみ置換する   私はこれを試しました:

#first by first I delete the old value
sed -i 's/speed:\(.\), //g' $FILENAME
sed -i 's/speed:\(..\), //g' $FILENAME
sed -i 's/speed:\(...\), //g' $FILENAME
sed -i 's/speed:\(....\), //g' $FILENAME

#then I've tried to calculate the new one
sed -i "s/server:\"\(192.168.0...\)\"/server:\"\1\", speed:$( ping -c3 \\1 | grep rtt | cut -f 5 -d '/' ), /g" $FILENAME

しかし、それは機能しません:

不明なホスト \1

答え1

はい、配列と sed を組み合わせて使用​​する解決策を見つけました。

#delete the old values
sed -i 's/speed:\(.\), //g' "$FILENAME"
sed -i 's/speed:\(..\), //g' "$FILENAME"
sed -i 's/speed:\(...\), //g' "$FILENAME"
sed -i 's/speed:\(....\), //g' "$FILENAME"

#create an array with just the urls
SERVER=( $(sed -nre 's/.*server:"(.*)".*/\1/p' "$FILENAME") )

#for each element
for element in $(seq 0 $((${#SERVER[@]}-1)))
do
    #calculate the new average ping speed
    SPEED[element]="$( sudo ping -c2 "${SERVER[element]}" | grep rtt | cut -f 5 -d '/' )"

    #if server is not available
    if [ -z "${SPEED[element]}" ]; then SPEED[element]=1000 ; fi

    #add the old server speed
    sed -i "s/\"\(${SERVER[element]}\)\"/\"\1\", speed:${SPEED[element]}/g" "$FILENAME"
done

パフォーマンスは良くないかもしれないが、機能し、役に立つかもしれない

関連情報