Beyond Ocean Beyond Ocean -4 years ago 110
Bash Question

how to write a linux shell variable to a file's given line?

I tried to Realize the function shown as the below FAKE code: to compute the net down rate and update the net log.
May somebody show me the right code? Thanks.


sed -i '1 cnet_link_error_total=$net_link_error_total' yy.log
sed -i '2 cnet_link_ok_total=$net_link_ok_total' yy.log

net_link_ok_rate=net_link_ok_total/(net_link_ok_total+net_link_error_total) * 100%
sed -e "3c net_link_ok_rate= /$net_link_ok_rate" yy.log


After I executed
sed -i '2 cnet_link_ok_total=$net_link_ok_total' yy.log

  • The yy.log is

  • BUT I want it to be

Answer Source

In the first two sed commands, variables are not expanded within single quotes.

Your last command applied to third line will works as intended but it's a good practice to restrict expansion to only variables, and not to enclose whole sed command within double quotes. Moreover I would add a space after each sed c commands for readability:

sed -i  '1c net_link_error_total='"$net_link_error_total"'' yy.log
sed -i  '2c net_link_ok_total='"$net_link_ok_total"'' yy.log

sed -e '3c net_link_ok_rate= /'"$net_link_ok_rate"'' yy.log

Also your rate calculation is wrong. You can use bc for this:

net_link_ok_rate=$( echo "scale=2; $net_link_ok_total/($net_link_ok_total+$net_link_error_total) * 100" | bc) 

Finally, note that with your last sed command the file will not be edited in place, as the -i flag is missing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download