我有一个 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
也许没有表现,但它有效并且可能有用