在特定上下文中以運算結果取代檔案中的值

在特定上下文中以運算結果取代檔案中的值

我有一個 JSON 物件數組,其中包含內部本地 url 和速度參數,就像[{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

也許沒有表現,但它有效並且可能有用

相關內容